C++ Class Header 和实现错误

C++ Class Header and Implementation Error

我最近才开始在 C++ 中处理单独的 class 文件,这是我的第一次尝试:

首先我做了一个 class header 叫做 "ThisClass.h":

//ThisClass.h

#ifndef THISCLASS_H
#define THISCLASS_H

class ThisClass
{
private:
    int x;
    float y;

public:
    ThisClass(int x, float y);
    void setValues(int x, float y);
    int printX();
    float printY();
};
#endif // THISCLASS_H

然后,我在一个名为 "ThisClass.cpp":

的文件中实现了我的 class
//ThisClass.cpp

#include "ThisClass.h"

ThisClass::ThisClass(int x, float y)
{
    this->x = x;
    this->y = y;
}

void ThisClass::setValues(int x, float y)
{
    this->x = x;
    this->y = y;
}

int ThisClass::printX()
{
    return this->x;
}
float ThisClass::printY()
{
    return this->y;
}

最后,我创建了一个名为 "main.cpp" 的文件,其中我使用了 class:

//main.cpp

#include <iostream>

    using namespace std;

    int main()
    {
        ThisClass thing(3, 5.5);
        cout << thing.printX() << " " << thing.printY()<< endl;
        thing.setValues(5,3.3);
        cout << thing.printX() << " " << thing.printY()<< endl;
        return 0;
    }

然后我通过使用 MinGW 编译器的代码块编译并 运行 这个程序并收到以下错误:

In function 'int main()':|
main.cpp|7|error: 'ThisClass' was not declared in this scope|
main.cpp|7|error: expected ';' before 'thing'|
main.cpp|8|error: 'thing' was not declared in this scope|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

我是不是做错了什么?任何帮助将不胜感激。

您在 main.cpp 中忘记 #include "ThisClass.h"

如前所述,您忘记将 #include "ThisClass.h" 放入 main.cpp

只要这样做,您的代码就会被编译。 我只想回答你的问题—— 但是,现在即使我有 2 个 cout 调用,我的控制台也没有输出任何内容 请在 main 函数的 return 之前放置一个 getchar(),这样您就可以看到您的输出。