注册 登录
编程论坛 C++教室

函数重载问题

sunlin1234 发布于 2015-04-11 17:53, 531 次点击
#include<iostream>

using namespace std;
class Complex
{

public:
    Complex(){real=0,imag=0;}
    Complex(double r,double i){r=real;i=imag;}//设置实部和虚部的变量
    Complex operator+(Complex c2);//申明重载函数运算符的额+的函数
    void display();//输出函数
private:
    double real;
    double imag;
};

Complex Complex::operator+(Complex c2)//定义重载运算符+
{ Complex c;
    c.real=real+c2.real;
    c.imag=imag+c2.imag;
    return c;
}
void display() //输出
{ cout<<"("<<real<<","<<imag<<")";}
int main()
{
    Complex c1(3,4),c2(5,-10),c3;
    c3=c1+c2;
    cout<<"c1=";c1.display();
    cout<<"c2=";c2.display();
    cout<<"c1+c2=";display();
    return 0;
}
错误是G:\vc6.0\anzhuang\MSDev98\Bin\重载.cpp(24) : error C2065: 'real' : undeclared identifier
G:\vc6.0\anzhuang\MSDev98\Bin\重载.cpp(24) : error C2065: 'imag' : undeclared identifier
求解决。谢谢
4 回复
#2
诸葛欧阳2015-04-11 18:39
设置实部虚部那个函数,里面赋值语句反了real=r;imag=i;
#3
bravetang2015-04-12 23:48
回复 楼主 sunlin1234
+1,不过重载函数的定义可以优化一下:

Complex Complex::operator+(const Complex& c2)const//定义重载运算符+
{
    return Complex (real+c2.real,imag+c2.imag);
}
#4
AleTiff2015-04-13 12:26
看仔细:

void display() //输出
{
    cout<<"("<<real<<","<<imag<<")";
}

编译器是在抗议你上面那个函数里的 real 变量。编译器找不到这个变量,我查你代码,并没有在哪个全局的位置里,声明了这个 real 。
噢,
另外一个 imag,也是没有声明过的。

[ 本帖最后由 AleTiff 于 2015-4-13 12:28 编辑 ]
#5
AleTiff2015-04-13 12:30


不好意思,是你 display() 成员函数,写成了普通函数。

你应该在写成 Complex::display() 这样的。哈哈哈哈。
1