c++中的类额对象_this指针

this指针的工作原理:类的成员函数(存放在代码区只有一份)默认添加了一个参数(类型*const this)指向调用该函数的对象

常函数(const修饰的成员函数):不能通过this指针修改this指向的对象内容(const person *const this)

class person(){

public :

void show(){   //编译器对其内部做了优化添加了一个this指针

cout<<a<<endl;    //this—>a

}

//常函数

void add()const{  

}

};

简单应用:用两对象中的成员相加为新对象成员初始化

class ming{

public :

ming(int a,string b){

age=a;

name =b;

}

ming add( ming&p){   

ming p(this.age+p.age,this.name+p.name);

return p;

}

int age;

string name;

};

void1 test01(){

ming p1(10,"bo");

ming p2(20,"ke");

ming p3=p1.add(p2);

}

posted @ 2022-04-12 18:08  spking  阅读(31)  评论(0)    收藏  举报