c++ - OOP 和类组合错误

标签 c++ oop

所以我有三个类,我们称之为汽车、发动机和定子电机。它们中的每一个都依赖于另一个。所以汽车有发动机,发动机有定子电机。

这是我在 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/

相关文章:

Java 泛型 : Foo<T>, Foo、Foobar<T extends Foo<T>> 和 Foobar<T extends Foo>

c++ - 如何在 Visual Studio 2005 中创建 ATL/C++ ActiveX DLL

c++ - C & C++ 中 sizeof() 运算符的返回值

c++ - 在 Linux 上使用 MinGW 交叉编译 C++ 代码,目标是 Windows : error happens

java - java中外部类和内部类是如何关联的?

php - 我应该使用 public setter 在类中设置私有(private)属性值吗?

c++ - 如何在单独的目录中运行带有 DLL 的 .exe?

c++ - 使用函数指针时,ESP 未在函数调用中正确保存

php - php包装器类中的instanceof错误

Java在不同的类中调用void方法到主类中?