c++ - 避免将 header 重新声明为源文件

标签 c++

假设我有两个文件 foo.h 和 foo.cpp

foo.h

class foo
{
    public:
        Foo(); 
        ~Foo(); 
    private:
        /*
        Member functions
        */
        static void DoThis();
        /*
        Member variables
        */
        static int x;


    protected:  
};

foo.cpp

#include "foo.h"

int foo::x;

void foo::DoThis()
{
    x++;
}

我可以避免在 foo.cpp 中再次声明每个变量的麻烦吗?如果我删除此行 int foo::x; 我会收到未解析的外部符号的链接器错误。

有没有另一种方法可以做到这一点,而不必为我计划使用的每个变量键入一行?

最佳答案

只需要重新声明静态变量即可。如果你在类定义中创建一个变量而不是静态的,你可以把它们留在那里。示例:

foo.h

#ifndef _FOO_H_
#define _FOO_H_

class Foo{
private:
  static int i; //Static variable shared among all instances
  int o; //Non-static variable remains unique among all instances
public:
  Foo(); //Consructor
};

#endif

foo.cpp

int Foo::i = 0; //Only static variables can be initialized when in a class
//No definition required for non-statics

Foo::Foo(){
  //Constructor code here
  i = 0;
};

#ifndef block 可防止 header 意外地被同一源文件多次包含。这是为了防止一个 header 包含在另一个 header 中,如果这些 block 不存在,可能会导致无限包含循环,并在计算包含深度过高时强制编译器退出。

关于c++ - 避免将 header 重新声明为源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26446306/

相关文章:

c# - 无法在列表中将类型 'uint' 隐式转换为 'T'(来自类模板)

c++ - 未解析的外部符号,在函数 _main 中引用

c++ - 用于简单包含在大型项目中的单线程共享指针

c++ - Qt QToolBar get按钮添加addAction

c++ - 将多个参数作为单个宏参数传递

c++ - 如何在字符串中搜索 C++

c++ - 迭代 C++ 中的类继承

c++ - OpenCV:HSV inRange 返回压缩和重复的二值图像

c++ - 使用鼠标滚轮时如何更新光标?

c++ - 如何使用 gcc 内联汇编代码访问成员变量