cancanword 2022-08-17 23:53 采纳率: 88.9%
浏览 41
已结题

C++头文件声明cpp定义失败

问题遇到的现象和发生背景

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定义的正确方法是什么呢,希望不吝赐教

  • 写回答

2条回答 默认 最新

  • 浪客 2022-08-18 00:03
    关注

    你用的什么编译器呢。
    需要把2个cpp文件都编译
    g++ main.cpp fushu.cpp -o main.exe

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 8月26日
  • 已采纳回答 8月18日
  • 创建了问题 8月17日

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效