c++ - 从 .h 文件中获取类变量,在 .cpp 文件中

标签 c++

我是 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 widthint 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/

相关文章:

c++ - 为 tic-tac-toe 实现 minimax 算法

boost::shared_ptr vector 的 C++ 静态初始化

C++/VS2008 : Performance of Macros vs. 内联函数

c++ - 如果构造函数发生异常,如何释放动态内存?

c++ - 生成随机数并在控制台上打印它们 (C++)

c++ - 基于堆栈缓冲区的STL分配器?

c++ - 为什么操作系统不拒绝为该程序分配内存?

c++ - 新对象导致堆损坏

C++11 无锁序列号生成器安全吗?

c++ - boost::uuids::uuid 作为 std::unordered_map 中的键?