问题描述
- 类模版对运算符重载以及输入输出重载
-
#include
//using namespace std;
template
class Complex
{
public:
friend istream& operator >> (istream &input,Complex &c)
{
cin >> c.real >> c.imag;
return input;
}
friend ostream& operator << (ostream &output,Complex &c)
{
cout << "(" << c.real << "+" << c.imag << "i)" << endl;
return output;
}
//friend istream & operator >> (istream &input,Complex &);
//friend ostream & operator << (ostream &output,Complex &);
Complex(T r,T i)
{
real = r;
imag = i;
}
Complex(){}
Complex operator + (Complex &c2)
{
return Complex(real + c2.real,imag + c2.imag);
}Complex operator * (Complex &c2) { return Complex(real * c2.real,imag * c2.imag); } Complex operator % (Complex &c2) { return Complex(real % c2.real,imag % c2.imag); } Complex operator - (Complex &c2) { return Complex(real - c2.real,imag - c2.imag); }
private:
T real,imag;
};
//templateint main()
{
Complexc1,c2,c3;
cout << "请输入第一个对象的实部和虚部" << endl;
cin >> c1;
cout << "请输入第一个对象的实部和虚部" << endl;
cin >> c2;
c3 = c1 + c2;
cout << c3;
c3 = c1 - c2;
cout << c3;
c3 = c1 * c2;
cout << c3;
c3 = c1 % c2;
cout << c3;
return 0;}
解决方案
C++重载<<和>>(输入输出运算符)
C++ 输入输出运算符重载
重载输入输出运算符
时间: 2024-12-02 03:37:44