调用方法时C cout.不知道我在做什么错

C++ Cout when calling methods. Dont know what im doing wrong

本文关键字:什么 不知道 方法 cout 调用      更新时间:2023-10-16

我是编码的新手,而我只是与C 一起玩,试图学习课程,什么不是。这是以下代码,我不知道为什么它不起作用。

我已经谷歌搜索了一段时间,找不到任何东西。

main.cpp

#include "Vehicle.cpp"
#include <iostream>
using namespace std;
int main() {
    Vehicle myVehicle();
    cout << myVehicle.testCout();
}

车辆.cpp

#include <iostream>
#include <string>
#include "Engine.cpp"
#include "Body.cpp"
#include "Rims.cpp"
using namespace std;
class Vehicle {
    Vehicle() {
        Engine engine(4, 1.6, "i4");
        Body body("black", 4);
        Rims rims(16);
    }
    void testCout() {
        cout << engine.getCylinders();
    }
};

main.cpp:E0153表达式必须具有类类型对象

车辆.cpp:E0020标识符"引擎"是未定义的

class Vehicle {
    Vehicle() {
        Engine engine(4, 1.6, "i4");
        Body body("black", 4);
        Rims rims(16);
    }
    void testCout() {
        cout << engine.getCylinders();
    }
};

问题是您的实例变量是不存在的。您的构造函数会创建一些变量,但是在CTOR结束后将其删除。您需要将它们保存在班上。

class Vehicle {
    Engine engine;
    Body body;
    Rims rims;
    public: // And you need to declare the stuff public that you want public
    Vehicle() {
        engine = Engine(4, 1.6, "i4");
        body = Body("black", 4);
        rims = Rims(16);
    }
    void testCout() {
        cout << engine.getCylinders();
    }
};

我不知道您是否发布了实际代码的混搭,但我看不到如何在班级外拨打私人成员。

为什么包含.cpp文件?

Vehicle.cpp: E0020 identifier "engine" is undefined

和上述错误是因为编译器找不到发动机类的声明。同样,对于您要创建的其他对象。