C++ 最常见的显示使用this 指针场景
2015-11-15 00:30
1226 查看
有一种场景必须显示使用this指针,需要将一个对象整体引用而不是引用对象的一个成员时。最常见的情况是在成员函数中使用this,返回对调用该函数的对象的引用。
如上面代码,成员函数返回对象的引用,可以实现一系列操作在一个表达式中完成,非常cool:
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 则使用的是成员变量
#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; }
如上面代码,成员函数返回对象的引用,可以实现一系列操作在一个表达式中完成,非常cool:
<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 则使用的是成员变量
相关文章推荐
- effective c++尽量少做转型动作(1)
- C++新手1024.cpp试制
- 软件工程(C编码实践篇)学习总结
- C语言
- 关键字static在c与c++中的区别。
- c语言的数组
- 《more effective c++》条款26 限制类对象的个数
- static_assert 是在编译时期的断言
- C/C++全局,静态变量小结
- Visual C++ Tips: 创建 SQLite 静态库
- C++ Polymorphism practice
- C-函数杂谈
- C-复杂的声明的阅读
- C-指针数组与数组指针
- C- 函数与指针
- C-字符串
- c++ 枚举的定义、设置值、取值范围
- C++实现单链表
- STL: lower_bound, upper_bound用法(C++)
- 11.c/c++程序员面试宝典-文件输入与输出