c++类与对象练习题-返回什么好呢?

此题主要考察this指针,以及引用作左值

#include <iostream>
using namespace std;
class A
{
   public:
      int val;

      // 在此处补充你的代码
      A(int x = 123 )
      {
         val = x;
      }

//************这部分我想了好久也没想出来
      A&  GetObj()
      {
         return *this;
      }
//**************很精髓     结论:返回左值尽量是 this指针指向的对象
};


int main()
{
   int m,n;
   A a;

   cout << a.val << endl;//输出 1,2,3

   while(cin >> m >> n)
   {
      a.GetObj() = m; //m被强制转换成另一个a类型
      cout << a.val << endl;
      a.GetObj() = A(n);
      cout << a.val<< endl;
   }
   return 0;
}


猜你喜欢

转载自blog.csdn.net/pursue_my_life/article/details/80783124