G ++不接受C ++中的内联构造函数 [英] G++ won't accept inline constructors in C++
问题描述
我有一个问题,可能是哑的。
事情是,我无法内联一个类中的构造函数。
考虑我有一个名为Foo的类。
如果我写的Foo的实现像这样:
class Foo {
int p;
public:
Foo(){p = 1; }
};
或甚至像这样:
class Foo {
int p;
public:
Foo();
};
inline Foo :: Foo(){
p = 1;
}
程序将无法编译。
我使用标准方法使用类:
Foo obj;
现在当我运行g ++ main.cpp foo.cpp时,我得到:
/tmp/ccyVtxvp.o:在函数main中:
main.cpp :(。text + 0x17):undefined引用` Foo :: Foo()'
collect2:ld退回1退出状态
时间,当我使用相同的代码,编译类作为共享库(工厂函数返回对象指针)后,它工作正常。
任何猜测为什么是否正在发生?
内联函数必须在使用它们的每个源文件中定义。实现这个的最简单的方法是将函数的定义(body)放在头文件中,并在函数使用的地方包含头
I have a problem, may be dumb.
The thing is, I am unable to inline a constructor in a class.
Consider I have a class called Foo.
If I write the implementation of Foo something like this:
class Foo {
int p;
public:
Foo() { p = 1; }
};
or even like this:
class Foo {
int p;
public:
Foo();
};
inline Foo::Foo() {
p = 1;
}
The program won't compile.
I use the class using the standard method:
Foo obj;
Now when I run g++ main.cpp foo.cpp, I get:
/tmp/ccyVtxvp.o: In function `main':
main.cpp:(.text+0x17): undefined reference to `Foo::Foo()'
collect2: ld returned 1 exit status
At the same time, when I use the same code, after compiling the class as a shared library (with factory functions to return object pointer), it works properly.
Any guesses why this is happening?
Inline functions must be defined in every source file in which they are used. The easiest way to achieve this is to put the definition(body) of the function in the header file and include the header wherever the function is used
这篇关于G ++不接受C ++中的内联构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!