十二章 类————返回自身类型的引用*this const

来源:互联网 发布:珠穆朗玛软件下载 编辑:程序博客网 时间:2024/06/07 11:31

 #include <iostream>
#include <conio.h>
using namespace std;

class Test
{
public:
 Test() { m_int = 0; }
 ~Test(){};
protected:
private:
 int m_int;
public:
 Test& get();
 Test& move();
 Test& display() const;
};

Test& Test::display() const
{
 cout<<"display m_int"<<m_int<<endl;
}

inline Test& Test::move()
{
  m_int++;
  return *this;
}

inline Test& Test::get()
{
 cout<<m_int<<endl;
 return *this;
}

int main()
{
 Test t1;
 t1.move().get();//1

 t1.move().get().display();//2  2

 t1.display().get();// 出现乱码  display()是const成员函数
 
 t1.get();// 2
    getch();
 return 0;
}