所以我有三个类,我们称之为汽车、发动机和定子电机。它们中的每一个都依赖于另一个。所以汽车有发动机,发动机有定子电机。
这是我在 C++ 中声明类的方式:
class Car {
private:
bool Has_Windows;
Engine _Eng_;
public:
Car(bool Windows, Engine _Eng): Has_Windows(Windows), _Eng_(_Eng){}
};
Class Engine {
private:
bool Racing_Car;
Stator_Motor s_motor;
public:
Engine(bool Car_Type_Engine, Stator_Motor _s_motor): Racing_Car(Car_Type_Engine),
s_motor(_s_motor){
}
};
Class Stator_Motor {
private:
bool AC_220;
public:
Stator_Motor(bool Voltage_Type): AC_220(Voltage_Type);
};
在 main 中,我将 C 初始化为:
Car C(true, Engine(true, Stator_Motor(true)));
现在问题来了,虽然当我写下它时,Visual Studio 中的智能感知确实找到了 Stator_Motor 构造函数定义,但是一旦我键入它,它就会说找不到具有相似参数的引擎定义。这是为什么?
最佳答案
在 C++ 中,您需要在使用符号之前声明您正在使用的符号。由于您不对类使用指针或引用,因此您实际上必须在使用它们之前定义它们。
所以你必须以相反的顺序定义类:
class Stator_Motor { ... };
class Engine { ... };
class Car { ... }
此外,您在 Stator_Motor
中的构造函数命名错误。
关于c++ - OOP 和类组合错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19903412/