C++快速入门P26运算符重载课上代码
#include <iostream>#include <string>
class Complex
{
public:
Complex();//构造器
Complex(double a,double b);//函数重载
virtual ~Complex();
Complex operator + (Complex &d);
void print();
private:
double real;//实部
double imag;//虚部
};
Complex::Complex()
{
real = 0;
imag = 0;
std::cout << "Complex 构造器++\n";
}
Complex::Complex(double r,double i)
{
real = r;
imag = i;
}
Complex::~Complex()
{
std::cout << "Complex 析构器--\n";
}
void Complex::print()
{
std::cout << "real = " << real << ",imag =" << imag << "\n";
}
Complex Complex::operator+(Complex &d)
{
Complex c;
c.real = real + d.real;
c.imag = imag + d.imag;
return c;
}
int main()
{
Complex a(1,2), b(1,4), c;
c = a + b;
std::cout << "a:";
a.print();
std::cout << "b:";
b.print();
std::cout << "c:";
c.print();
return 0;
} #include <iostream>
class Complex
{
public:
Complex();// 构造器
Complex(double a, double b);// 函数重载
~Complex();
Complex operator+(const Complex &c);// 运算符重载
void print();
private:
double real;// 实部
double imag;// 虚部
};
Complex::Complex()
{
real = 0;
imag = 0;
std::cout << "调用了无参构造函数" << std::endl;
}
Complex::Complex(double a, double b)
{
real = a;
imag = b;
std::cout << "调用了带参构造函数" << std::endl;
}
Complex::~Complex()
{
std::cout << "调用了析构函数" << std::endl;
}
Complex Complex::operator+(const Complex &c)
{
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
void Complex::print()
{
std::cout << "(" << real << " + " << imag << "i)" << std::endl;
}
int main()
{
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
Complex result = c1 + c2;
result.print();
return 0;
}
这是一个简单的复数类,通过运算符重载实现了复数的加法运算。在类中,我们定义了一个无参构造函数和一个带参构造函数,用于初始化实部和虚部。然后,我们重载了"+"运算符,实现了两个复数对象之间的加法运算。最后,在main函数中,我们创建了两个复数对象c1和c2,并进行加法运算,将结果赋给result对象,并通过调用print函数打印出结果。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页:
[1]