【问题标题】:declare a class member function to use before linking在链接之前声明要使用的类成员函数
【发布时间】:2012-05-18 14:24:33
【问题描述】:
我想使用一个存在于其他模块中并且可用于链接的类。头文件的大小很大,所以我不想在当前模块中包含头文件。
我正在尝试通过
转发声明类
类 foo;
int foo::getValue();
这里 getValue() 是我要使用的 foo 的成员函数。
现在,当我编译代码时,在链接为之前出现编译错误
error: forward declaration of 'struct foo'
我在这里错过了什么?
谢谢,
【问题讨论】:
标签:
c++
compilation
linker
【解决方案1】:
您不能转发声明类成员,您需要包含整个标题。
这里正确的做法是减小标头的大小。如果它只包含类定义,则保持原样。如果没有,则有可能将其分解为多个标题。
如果类定义很大,这表明你的设计有缺陷并且可能会被破坏。
【解决方案2】:
仅当您不需要了解类的内部结构(即成员和/或大小)时,才可以使用类的前向声明。
这种技术的典型使用涉及类指针或引用:
class included_class;
class encapsulating_class
{
public:
void some_method(const& included_class_pointer) const;
private:
included_class * included_class_pointer;
};
使用此技术无法尝试以您指示的方式转发声明类内部,并且需要包含类头。