-1

我在单个 cpp 文件 ( tested.cpp) 中有以下代码:

class tested {
        private:
                int x;
        public:
                tested(int x_inp) {
                        x = x_inp;
                }

                int getValue() {
                        return x;
                }
};

现在我想为这段代码写一个头文件。它应该怎么看?有了头文件后,我应该在我的 cpp 文件中更改什么。我想我的头文件应该是这样的:

class tested {
   private:
      int x;
   public:
      tested(int x);
      int getValue();
}

然后在我的 cpp 文件中我应该#include "tested.h". 我还需要通过以下方式替换整个班级:

tested::tested(int c_inp) {
   x = x_inp;
}

tested::getValue(){
   return x;
}

这样对吗?

4

3 回答 3

2

为了使您的头文件更通用,您可以使用#ifndef这里 的宏http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html

于 2013-04-18T09:22:29.700 回答
1

您还需要为构造函数和析构函数以外的方法键入返回类型:

int tested::getValue(){
   return x;
}
于 2013-04-18T08:48:07.457 回答
1

是的,正如弗洛伊德之前所说,通常使用#ifndef 来保护头文件免受多次包含(尤其是在大型项目中,或者如果您的文件可能是其中的一部分)。

其他一些事情(基本上是风格问题):

  • 不必为类的第一个成员输入“private:”,因为默认情况下所有类成员都是私有的。
  • 通常在类的每个属性的名称之前(或之后)放置一个字符(例如“x_”而不是“x”)
于 2013-04-18T11:08:29.757 回答