当前位置: 代码迷 >> 综合 >> C++ 类的 this 指针 语法练习
  详细解决方案

C++ 类的 this 指针 语法练习

热度:23   发布时间:2024-01-19 15:39:19.0

 

#include <iostream>
#include <string>
using namespace std;
// 定义一个类 Student
class Student
{
private:
string name;
int    age;
string address;
public:
// 存
void setname(string s){	name = s;}
void setage(int y){age = y;	}
void setaddress(string add){address = add;}    
// 取
string getname(){return name;}
int getage(){return age;}
string getaddress(){return address;}
void Show()
{ cout<<"this = "<<this<<endl;}
protected:
};
int main(void)
{
Student x;  	
x.Show();
cout<<"&x   = "<<&x<<endl;	  
// 以上表明this指向的就是当前的对象x
cout<<"----------------------"<<endl;
Student y;
y.Show();
cout<<"&y   = "<<&y<<endl;	  
// 以上表明this指向的就是当前的对象y
// --------------------
return 0;
}


第一次调用时,this地址与对象x的一样;

第二次调用是,this地址与对象y的一样.

  相关解决方案