您的位置:首页 > 编程语言 > C语言/C++

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

2012-10-03 04:25 176 查看
#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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: