富人 2016-07-28 10:22 采纳率: 50%
浏览 1001
已采纳

C++一个小程序,关于运算符重载,无法运行,不知道哪里出错。

我在做一个练习,关于运算符重载的,写了一个重载+ 运算符的小程序,目的是输出K的实部和虚部,但无法运行,求前辈指导!谢谢大家。
代码如下:

#include "iostream"

using namespace std;

class Complex
{
private:
double real;
double image;

public:
Complex(double r = 0.0, double i = 0.0);
Complex operator + (const Complex &);

double getComplexReal();
double getComplexImage();

};

double Complex::getComplexReal()
{
return real;
}

double Complex::getComplexImage()
{
return image;
}

Complex Complex::operator+(const Complex & operand2)
{
return Complex(real + operand2.real, image + operand2.image);
}

int main()
{
Complex m(1.0,2.0),n(2.0,3.0),k;
k = m + n;
cout<<"K's real is:"<<k.getComplexReal()<<". and image is:"<<k.getComplexImage()<<endl;
}

  • 写回答

2条回答 默认 最新

  • luoluolzb 2016-07-28 11:02
    关注

    很明显的错误,Complex构造函数只有声明没有定义啊, 其他的没有问题。
    完整代码:

     #include "iostream"
    using namespace std;
    
    class Complex
    {
    private:
        double real;
        double image;
    
    public:
        Complex(double r = 0.0, double i = 0.0): real(r), image(i) {}
        Complex operator + (const Complex &);
        double getComplexReal();
        double getComplexImage();
    };
    
    
    double Complex::getComplexReal()
    {
        return real;
    }
    
    double Complex::getComplexImage()
    {
        return image;
    }
    
    Complex Complex::operator+(const Complex & operand2)
    {
        return Complex(real + operand2.real, image + operand2.image);
    }
    
    int main()
    {
        Complex m(1.0,2.0),n(2.0,3.0),k;
        k = m + n;
        cout<<"K's real is:"<<k.getComplexReal()<<". and image is:"<<k.getComplexImage()<<endl;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘