this指针的用法:在类中使用this可以让代码更加清晰易读
#include <iostream>
#include <string>
using namespace std;
/* 定义一个Person类 */
class Person
{
public:
Person(const std::string &name, const std::string address)
{
/* this指代当前对象 可以省略 */
/* 如果写上的话代码看起来更加清晰 */
this->name = name;
this->address = address;
}
std::string getName() const
{
return this->name;
}
std::string getAddress() const
{
return this->address;
}
private:
std::string name;
std::string address;
};
int main()
{
Person p("Bill","beijing");
cout << "test" << endl;
cout << p.getName() << " " << p.getAddress() << endl;
return 0;
}
返回this的使用
#include <iostream>
#include <string>
using namespace std;
// 定义一个文本类
class Screen
{
public:
typedef std::string::size_type index;
Screen(index ht = 0, index wd = 0):contents(ht*wd, 'A'),cursor(0),height(ht),width(wd)
{
/* 构造函数
index ht :高度
index wd :宽度
初始化列表
contents(ht*wd, 'A') :文本内容 同:string(1000 'A')
cursor(0) :文本下标为0 起始位置
height(ht) :高度
width(wd) :宽度
*/
};
char get() const { return contents[cursor];}
char get(index r, index c) const{
index row = r * width;
return contents[row + c];
};
/* 注意这里的函数的类型Screen& */
/* 函数返回值的类型是个对象 */
/* 这样有什么好处?往下看 */
Screen& move(index r, index c);
void set(index r, index c, char x);
Screen& set(char c);
Screen& display(std::ostream &os)
{
do_display(os);
return *this;
}
private:
std::string contents;
index cursor;
index height, width;
void do_display(std::ostream &os) const
{
os << contents;
}
};
Screen& Screen::move(index r, index c){
index row = r * width;
cursor = row + c;
return *this;
}
void Screen::set(index r, index c, char x){
index row = r * width;
contents[row + c] = x;
}
Screen& Screen::set(char c){
contents[cursor] = c;
return *this;
}
int main()
{
Screen myScreen(5, 3);
myScreen.get(); // 获得cursor 起始位置的内容
myScreen.get(3,2); //获得第3行第2+1列位置的内容
myScreen.set(3, 2, 'B'); //将第3行第2+1列位置的内容改成'B'
myScreen.move(4, 1); // 将cursor 移动到第4行1+1列的位置
myScreen.set('C'); // 将当前cursor 位置的内容改成'C'
/* 到现在好像没看出什么来 */
/* 马上就是见证奇迹的时刻 */
myScreen.move(2,1).set('X').move(2,2).set('Y');
myScreen.display(cout);
cout << endl;
/* 这就是*this的用法 */
/* 返回的是一个对象,后序可以继续对对象进行操作 */
return 0;
}