每日100!
自引用指针 this
//1表示内存地址
#include
using namespace std;
class This {
int a;
public:
This(int aa){
a = aa;
}
void print(){
cout << “内存地址:” << this << endl;
cout << "a = " << a << endl;
}
};
//2 this->x = x;
class This2 {
int x,y;
public:
This2(int x = 0,int y = 0){
this->x;
this->y;
}
void judge (This2 &A){
if(this == &A){
cout << “the same” << endl;
} else{
*this = A;
}
}
void print(){
cout << “x =” << x << endl;
cout << “y =” << y << endl;
}
};
//3返回*this
class This3 {
private:
double real,imag;
public:
This3(double r = 0.0,double i = 0.0){
real = r;
imag = i;
}
This3 Add(This3 C,This3 D);
double GetR() {
return real;
}
double GetI() {
return imag;
}
};
This3 This3::Add(This3 C1,This3 C2) {
real = C1.real + C2.real;
imag = C1.imag + C2.imag;
return *this;
}
Main.cpp
#include “This.h”
#include “This2.h”
#include “This3.h”
#include
using namespace std;
int main(){
This A(1);
A.print();
cout << “------------------------------------------------------” << endl;
This2 B(4,5);
B.judge(B);
B.print();
cout << “------------------------------------------------------” << endl;
This3 C1(7.1,5.5),C2(4,4),C3;
cout << C3.Add(C1,C2).GetR() << " " << C3.Add(C1,C2).GetI() ;
return 0;
}