//5.5 成员运算符重载函数 #include<iostream> using namespace std; class Base{ public: Base(double i=0.0,double j=0.0); void print(); Base operator+(Base c); private: double real; double imag; }; Base::Base(double i,double j) { i=real; j=imag; } Base Base::operator+(Base c) { Base temp; temp.real=real+c.real; temp.imag=imag+c.imag; return temp; } void Base::print() { cout<<real; if(imag>0) cout<<"+"; if(imag!=0) cout<<imag<<'i'<<endl; } int main() { Base a1(2.3,4.6),a2(3.6,2.8),a3,a4; a3=a1+a2; a3.print(); return 0; }
时间: 2024-03-30 10:38:37 浏览: 224
这段代码是一个简单的C++程序,定义了一个名为Base的类,重载了成员运算符+。类的定义分为public和private两部分,其中public部分包括一个构造函数Base(double i=0.0,double j=0.0),一个成员函数void print(),以及一个成员运算符重载函数Base operator+(Base c)。private部分包括两个double类型的变量real和imag。在main函数中,定义了4个Base类型的对象a1、a2、a3和a4,其中a1和a2通过构造函数初始化,a3通过运算符重载函数实现a1+a2的操作,最后调用a3的print函数输出结果。
在运算符重载函数Base operator+(Base c)中,定义了一个Base类型的临时对象temp,实现了对real和imag成员变量的相加操作,并将结果存储到temp中,最后返回temp对象。
相关问题
将运算符+和-重载为 complex 类的友元函数。 #include<iostream.h> class complex { public: complex(double r=0.0,double i=0.0) { real=r; imag=i; } //构造函数 friend complex operator + (complex c1,complex c2); //重载运算符+为友元函数 friend complex operator - (complex c1,complex c2); //重载运算符-为友元函数 void display(); //显示复数的值 private: //私有成员 double real; double imag; }; 完成该类的实现并编译运行该程序。
以下是重载运算符+和-的实现:
```cpp
#include<iostream>
using namespace std;
class complex
{
public:
complex(double r = 0.0, double i = 0.0)
{
real = r;
imag = i;
}
void display()
{
cout << real << "+" << imag << "i" << endl;
}
friend complex operator+(complex c1, complex c2);
friend complex operator-(complex c1, complex c2);
private:
double real;
double imag;
};
complex operator+(complex c1, complex c2)
{
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
complex operator-(complex c1, complex c2)
{
return complex(c1.real - c2.real, c1.imag - c2.imag);
}
int main()
{
complex c1(1.0, 2.0), c2(2.0, 3.0);
complex c3 = c1 + c2;
complex c4 = c1 - c2;
c3.display(); // 输出 3+5i
c4.display(); // 输出 -1-1i
return 0;
}
```
运行结果:
```
3+5i
-1-1i
```
将运算符+和-重载为 complex 类的成员函数。 #include<iostream.h> class complex //复数类声明 { public: //外部接口 complex(double r=0.0,double i=0.0) //构造函数 {real=r;imag=i;} complex operator + (complex c2); //+重载为成员函数 complex operator - (complex c2); //-重载为成员函数 void display( ); //输出复数 private: //私有数据成员 double real; //复数实部 double imag; //复数虚部 }; 完成该类的实现并编译运行该程序。
以下是重载运算符+和-的 complex 类的实现代码:
```
#include<iostream>
class complex
{
public:
complex(double r = 0.0, double i = 0.0)
{
real = r;
imag = i;
}
complex operator+(complex c2)
{
return complex(real + c2.real, imag + c2.imag);
}
complex operator-(complex c2)
{
return complex(real - c2.real, imag - c2.imag);
}
void display()
{
std::cout << "(" << real << ", " << imag << "i)" << std::endl;
}
private:
double real;
double imag;
};
int main()
{
complex c1(1.0, 2.0);
complex c2(3.0, 4.0);
complex c3 = c1 + c2;
c3.display();
complex c4 = c1 - c2;
c4.display();
return 0;
}
```
运行结果:
```
(4, 6i)
(-2, -2i)
```
阅读全文