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

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

热度:87   发布时间:2024-01-19 15:38:21.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;}
/*
// 返回 指向Student 对象 : 因为this是指针,*this就是当前对象(的值) ?	
Student Show() 
{
cout<<"姓名: "<<name<<" --- 年龄: "<<age<<" ---- 住址: "<<address<<endl; 
return *this; // 这里不是this,而是 *this
}     
*/
// 或者 Student & Show() 就是返回对象的引用 也对.	  是返回引用好?还是上面的返回对象本身好?
Student & Show() 
{
cout<<"姓名: "<<name<<" --- 年龄: "<<age<<" ---- 住址: "<<address<<endl; 
return *this; // 这里不是this,而是 *this
}
protected:
};
int main(void)
{
Student x;	   
x.setname("柳絮飘");
x.setage(22);
x.setaddress("学明路115号");		  
// x.Show().Show().Show().Show(); // 注意不再是  x.Show()->Show()->Show()->Show();   
Student k;
// k= x.Show();  //或者 k= x.Show().Show().Show().Show(); 也对.
k= x.Show().Show().Show().Show(); 
// --------------------
return 0;
}


// --

 

问题是 返回对象好,还是返回对象的引用好?

 
  // 返回 指向Student 对象 : 因为this是指针,*this就是当前对象(的值) ? 
 Student Show()
 {
  cout<<"姓名: "<<name<<" --- 年龄: "<<age<<" ---- 住址: "<<address<<endl;
  return *this; // 这里不是this,而是 *this
 }    

    // 或者 Student & Show() 就是返回对象的引用 也对.   是返回引用好?还是上面的返回对象本身好?
 
    Student & Show()
    {
     cout<<"姓名: "<<name<<" --- 年龄: "<<age<<" ---- 住址: "<<address<<endl;
     return *this; // 这里不是this,而是 *this
    }

 

  相关解决方案