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
}
相关文章推荐
- C++ 类的 this 指针 语法练习
- C++ 类的 this 指针 语法练习2
- C++ 类的 this 指针 语法练习3
- C++ 类的 this 指针 语法练习4
- C++语法基础--类(class)--类型别名,this指针,初始化式,友元的一些注意细节
- c++主项练习错题分析(1) const,this指针
- 浅析C++中的this指针
- c++的this指针
- C++之指针(对象指针+对象成员指针+this指针[待补充])
- 语法:c++对关于空指针0/NULL/nullptr三者的演变
- C++文本查询程序 定义类管理数据 用智能指针 C++Primer练习12.30
- C++文本查询程序 定义类管理数据 用引用共享数据 不用智能指针 C++Primer练习12.27
- 浅谈C++的this指针
- C++中this指针的用法详解
- c++对象数组和this指针
- C++ 容器vector 语法练习
- C++语法基础--智能指针
- C++中this指针的用法
- C++析构函数,This指针,函数链
- 孙鑫MFC视频第二节代码练习(二)类的this指针,类的派生