我是 C++ 的新手,我的类定义有问题。这很可能是一个非常基本的操作,但我无法在线找到任何相关资源,因为我不太确定要搜索什么。
标题说明了一切。我有一个如下所示的头文件:
class Rectangle{
public:
int Width();
int Height();
int Area();
void Resize();
private:
int width;
int height;
}
然后我有以下 .cpp 文件。
int Rectangle::Width()
{
//return the width
}
int Rectangle::Height()
{
//return the height
}
int Rectangle::Area()
{
//return the area
}
void Rectangle::Resize()
{
//resize the rectangle
}
如您所见,我已经注释了我希望执行的操作,但我不太确定如何从中访问变量 int width
和 int height
头文件。
最佳答案
您所要做的就是确保在 .cpp
的顶部包含 class
头文件,如下所示...
#include "THE_FILE_NAME.h"
然后您就可以随意访问它们了。例如,要返回宽度和高度,只需执行以下操作:
int Rectangle::Width()
{
return width; //or this->width
}
int Rectangle::Height()
{
return height; //or this->height
}
关于c++ - 从 .h 文件中获取类变量,在 .cpp 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38085208/