问题遇到的现象和发生背景
C++新手,目的是想写一个头文件声明类方法,然后用一个cpp来定义类方法,最后再写一个main.cpp来调用类方法,可是终端却显示 “undefined reference to ”类方法,
问题相关代码,请勿粘贴截图
#ifndef COMPLEX_H_ //头文件
#define COMPLEX_H_
class fushu{
public:
fushu(double x1,double x2);
fushu operator + (const fushu&) const;
fushu operator - (const fushu&) const ;
fushu operator * (const fushu&) const;
friend fushu operator * (double,const fushu&);
fushu operator ~ () const;
private:
double a,b;
friend ostream& operator <<(ostream& os ,fushu& mod){
return os << "(" << mod.a << "," << mod.b << ")"<<endl;
}
friend std::istream& operator >>(istream&,fushu&);
};
#endif
#include <iostream> //用来定义类方法的cpp
using namespace std;
#include "complex0.h"
fushu::fushu(double x1=0,double x2=0):a(x1),b(x2){}
fushu fushu::operator * (const fushu& mod) const {
fushu x;
x.a=a*mod.a-b*mod.b;
x.b=a*mod.b+b*mod.a;
return x;
}
fushu fushu::operator + (const fushu& mod ) const {
fushu x;
x.a=a+mod.a;
x.b=b+mod.b;
return x;
}
fushu fushu::operator - (const fushu& mod) const {
fushu x;
x.a=a-mod.a;
x.b=b-mod.b;
return x;
}
fushu fushu::operator ~ ()const {
fushu x;
x.a=a;
x.b=-b;
return x;
}
fushu operator * (double x1,const fushu& mod) {
fushu x;
x.a=x1*mod.a;
x.b=x1*mod.b;
return x;
}
istream& operator >>(istream & is,fushu& mod){
}
#include <iostream> //main.cpp
using namespace std;
#include "complex0.h"
int main(){
fushu x1(2,3); //调试构造函数
cout << x1; //调试重载符
}
运行结果及报错内容
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\AppData\Local\Temp\cc9Ao64C.o:main.cpp:(.text+0x2f): undefined reference to `fushu::fushu(double, double)'
collect2.exe: error: ld returned 1 exit status
我的解答思路和尝试过的方法
尝试过把类方法的定义放到头文件里,然后就成功运行了
我想要达到的结果
所以实现头文件声明cpp定义的正确方法是什么呢,希望不吝赐教