C++ 将内联类成员函数声明和定义分离到不同的文件(头文件和源文件)
我有3个文件:main.cpp,gp_frame.cpp和gp_frame.h。我希望在gp\u frame.h中声明一个类(名为gp\u frame),并在gp\u frame.cpp中定义成员函数,并希望在main.cpp中使用该类 大体上,这三个文件:C++ 将内联类成员函数声明和定义分离到不同的文件(头文件和源文件),c++,class,oop,C++,Class,Oop,我有3个文件:main.cpp,gp_frame.cpp和gp_frame.h。我希望在gp\u frame.h中声明一个类(名为gp\u frame),并在gp\u frame.cpp中定义成员函数,并希望在main.cpp中使用该类 大体上,这三个文件: /*main.cpp*/ #include "gp_frame.h" void plotpicture(unsigned int a, unsigned int b, unsigned int c, unsigned int d, uns
/*main.cpp*/
#include "gp_frame.h"
void plotpicture(unsigned int a, unsigned int b, unsigned int c, unsigned int d, unsigned int e){
anita.wait_enter("Some string\n");
}
int main(){
gp_frame anita(true);
plotpicture(1,2,3,4);
return 0;
}
/*gp_frame.h*/
class gp_frame{
public: void wait_enter(std::string uzi);
gp_frame();
gp_frame(bool isPersist);
};
/*gp_frame.cpp*/
#include "gp_frame.h"
void gp_frame::wait_enter(std::string uzi){
/*Some of code*/
}
gp_frame::gp_frame(){
/*Some of code*/
}
gp_frame::gp_frame(bool isPersist){
/*Some of code*/
}
然后,我想编译并链接这些文件:
g++ -c main.cpp -w -Wall
g++ -c gp_frame.cpp -w -Wall
g++ gp_frame.o main.o -o Myprogram
而且一切正常。但是,如果我想声明/定义函数wait\u,请输入inline
like:
/*in gp_frame.h*/
public: inline void wait_enter(std::string uzi);
/*in gp_frame.cpp*/
inline void gp_frame::wait_enter(std::string uzi){
/*Some of code*/
}
编译器也可以工作,但链接器向我抛出一个错误:
main.o: In function `plotpicture(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int)':
main.cpp:(.text+0x2c6b): undefined reference to `gp_frame::wait_enter(std::string)'
collect2: error: ld returned 1 exit status
你能解释一下如何解决这个问题吗?我错在哪里
遗憾的是,
extern-inline
和static-inline
都不能解决我的问题
我错了什么
您声明了一个内联函数gp\u frame::wait\u enter(std::string)
,但没有在使用标准所需函数的所有编译单元(源文件)中定义该函数
特别是,您只在gp_frame.cpp
中定义了函数,而没有在main.cpp
中定义,即使您在main.cpp
中使用了函数
如何解决这个问题
在使用内联函数的所有编译单元中定义内联函数。惯用的方法是在同样声明它们的头中定义它们(
gp_frame.h
),内联函数必须在头中定义。只有在实现中定义的内联函数没有意义。编译器如何看到内联的定义?可能是