*this不能用于静态成员,只能用于非静态成员函数内部
*this指的是类的实例,用的形式为(this).xx或者this->xx
因为this是实例,所以直接cout<<*this就需要重载输出流运算符,因为输出对象
this是实例的地址,实例的指针
#include<iostream>
#include<iomanip>
using namespace std;
class CComplex {
private:
double r, i;
public:
CComplex(double r = 0, double i = 0) {
this->r = r;
this->i = i;
cout << "Constructor: " << "("<<this->r<<", " <<this->i<<")"<<endl;
};
~CComplex() {
cout<<"Destructor: "<<"("<< this->r << ", " << this->i << ")" << endl;
}
friend CComplex operator+(CComplex c1, CComplex c2);
friend ostream& operator <<(ostream& os, const CComplex& CTemp)
{
os << "(" << CTemp.r << ", " << CTemp.i << ")";
return os;
}
};
CComplex operator+(CComplex c1, CComplex c2)
{
CComplex CTemp;
CTemp.r = c1.r + c2.r;
CTemp.i = c1.i + c2.i;
return CTemp;
}
int main()
{
double r1, i1;
double r2, i2;
cin >> r1 >> i1;
cin >> r2 >> i2;
CComplex c1(r1, i1) , c2(r2, i2);
CComplex c3 = c1 + c2;
cout << c1 << endl;
cout << c2 << endl;
cout << c3 << endl;
}
这里的重载加法运算符用到了友元函数
这里出现问题的原因也是this指向静态成员了
重载加法运算符可以这样写,用&,因为这样就可以省略两个参数传过去的过程中调用拷贝构造,并且这个
CComplex CComplex:: operator+(const CComplex& b)
{
CComplex Temp;
Temp.r = this->r + b.r;
Temp.i = this->i + b.i;
return Temp;
}
并且这样*this也可以用了
改进后的代码
#include<iostream>
#include<iomanip>
using namespace std;
class CComplex {
private:
double r, i;
public:
CComplex(double r = 0, double i = 0) {
this->r = r;
this->i = i;
cout << "Constructor: " << "(" << this->r << ", " << this->i << ")" << endl;
};
~CComplex() {
cout << "Destructor: " << "(" << this->r << ", " << this->i << ")" << endl;
}
CComplex(CComplex& t)
{
this->i = t.i;
this->r = t.r;
cout << *this << "copy construction" << endl;
}
CComplex operator+(CComplex& b);
friend ostream& operator <<(ostream& os, CComplex& CTemp)
{
os << "(" << CTemp.r << ", " << CTemp.i << ")";
return os;
}
};
CComplex CComplex:: operator+( CComplex& b)
{
CComplex Temp;
Temp.r = this->r + b.r;
cout << *this<<endl;
Temp.i = this->i + b.i;
cout << *this<<endl;
return Temp;
}
int main()
{
double r1, i1;
double r2, i2;
cin >> r1 >> i1;
cin >> r2 >> i2;
CComplex c1(r1, i1), c2(r2, i2);
CComplex c3 = c1 + c2;
cout << c1 << endl;
cout << c2 << endl;
cout << c3 << endl;
}
运行处了两个(1,1),这个点嘛,*this指针指向最后的那一次c1输人,因为加法传参数从右往左传(我也不知道对不对,自己想的,保留疑问吧)