C++类 | 重复符号之外的成员函数定义
C++ member function definition outside the class | duplicate symbols
在我的一个类头文件Lfo.h
中,我有一个类定义,我将成员函数定义放在类之外(最好有一个单独的.cpp文件,但它应该可以放在这里?
// Lfo.h
class CLfo
{
public:
static int create (CLfo*& pCLfo);
};
int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
然后我还有另一个叫做CVibrato的课程:
// Vibrato.h
class CVibrato
{
public:
static int create (CVibrato*& pCVibrato);
private:
CVibrato();
};
和.cpp文件(在 cpp 文件中,我包含 Lfo.h,因为稍后颤音类将有一个 lfo 成员,但我现在还没有实现):
// Vibrato.cpp
#include "Lfo.h"
#include "Vibrato.h"
int CVibrato::create(CVibrato *&pCVibrato)
{
pCVibrato = new CVibrato();
return 0;
}
CVibrato::CVibrato()
{
}
然后我想在main()中创建颤音类的实例
#include "Vibrato.h"
#include "Lfo.h" // if comment this line out there will be no error, why is that?
int main()
{
CVibrato *vibrato = 0;
CVibrato::create(vibrato);
return 0;
}
但是我收到一个1 duplicate symbol for architecture x86_64
错误。什么是重复的?似乎原因是在Lfo.h中,我将成员函数的定义放在类之外,如果我把它放在里面,程序就可以正常运行。但我无法理解。在 C++ 中,我们不允许这样做吗?顺便说一句,如果我的一个类(在我的例子中是颤音)将具有另一个类(在本例中为 lfo)的类成员,我应该在 .h (vibrato.h) 文件或 .cpp (vibrato.cpp) 文件中包含成员类的头文件?
类是声明。声明不会生成任何代码。即使类中有一个成员函数,编译器也会将其视为inline
。函数体可以放在标头中,但应始终声明为inline
。编译器实际上可能不会内联它,但它会将其视为代码创建的单个实例。
任何时候您:
void function( ) { }
为该函数创建代码。如果多次包含标头,则会告诉编译器多次创建代码。但是所有函数都必须具有唯一的名称!所以你得到重复的错误。这就是为什么代码生成行属于.cpp
文件的原因。
"inline"告诉编译器不要创建即时代码,而是在使用点创建代码。
不能将类方法定义直接放在头文件中,除非显式将其标记为内联。如下所示:
// Lfo.h
class CLfo
{
public:
inline static int create (CLfo*& pCLfo);
};
int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
或
// Lfo.h
class CLfo
{
public:
static int create (CLfo*& pCLfo);
};
inline int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法