假设我有两个文件 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/