0

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

首先,我创建了一个名为“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”的文件中实现了我的类:

//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”的文件,并在其中使用了该类:

//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 编译器的 Code Blocks 编译并运行该程序并收到以下错误:

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)) ===|

我在某种程度上做错了吗?任何帮助,将不胜感激。

4

2 回答 2

2

你忘了#include "ThisClass.h"进去main.cpp

于 2016-07-20T11:28:38.813 回答
0

正如已经回答的那样,您忘记#include "ThisClass.h"放入main.cpp.

只需这样做,您的代码就会被编译。我只是想回答你的问题 - 但是,即使我有 2 个 cout 调用,现在我的控制台也没有输出任何内容。请在函数中添加 一个getchar()before ,它可以让你看到你的输出。returnmain

于 2016-07-20T12:13:40.143 回答