有一种场景必须显示使用this指针,需要将一个对象整体引用而不是引用对象的一个成员时。最常见的情况是在成员函数中使用this,返回对调用该函数的对象的引用。
#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <list>
#include <string>
class Screen
{
public:
typedef std::string::size_type index;
Screen();
//constructor
Screen(index h, index w, std::string cont) :height(h), width(w), contents(cont) {}
//get char where cursor points to
char get() const { return contents[cursor]; }
//get char where column and row points to
char get(index ht, index wd) const;
// get cursor
index get_cursor() const { return cursor; }
// set content where cursor points to
Screen& set(char);
//set content where column and row points to
Screen& set(index, index, char);
//move cursor to where column and row points to
Screen& move(index, index);
//show contents
const Screen& display(std::ostream& os) const;
private:
std::string contents;
index cursor;
index height;
index width;
};
Screen::Screen()
{
}
char Screen::get(index ht, index wd) const
{
index row = wd*width;
return contents[row + ht];
}
Screen& Screen::set(char c)
{
contents[cursor] = c;
return *this;
}
Screen& Screen::set(index r, index col, char c)
{
index row = r *width;
contents[row + col] = c;
return *this;
}
Screen& Screen::move(index r, index c)
{
index row = r*width;
cursor = row + c;
return *this;
}
const Screen& Screen::display(std::ostream& os) const
{
os << contents;
return *this;
}
int main(int argc, char* argv[])
{
Screen myScreen(5,2,"helloworld");
myScreen.move(4, 0).set('#').display(std::cout);
return 0;
}
<pre name="code" class="cpp">myScreen.move(4, 0).set('#').display(std::cout);
PS . 为什么使用return *this 只能返回使用该成员函数的对象的引用,而不是直接返类型对象?
答: 类定义体结束前,该类型是不完全类型,只能使用该类型的指针或引用
====================================
另外一种会显式使用this 指针的场景是: 成员函数形参变量与成员变量同名,在成员函数函数体中为了使用成员函数,则必须显式使用this 指针:
class test
{
int num;
void fuck(int);
}
void test::fuck(int num)
{
int shit = <span style="color:#ff0000;">num</span> + <span style="color:#ff0000;">this->num</span>;
}
如上,第一个num 使用的是形参,this->num 则使用的是成员变量