📜  C++ |这个指针|问题2

📅  最后修改于: 2021-05-25 21:33:11             🧑  作者: Mango

这个指针有什么用?
(A)当局部变量的名称与成员的名称相同时,我们可以使用此指针访问成员。
(B)返回对调用对象的引用
(C)可用于对象上的链式函数调用
(D)以上全部答案: (D)
说明:第一次使用时,请参见以下示例。

/* local variable is same as a member's name */
class Test
{
private:
   int x;
public:
   void setX (int x)
   {
       // The 'this' pointer is used to retrieve the object's x
       // hidden by the local variable 'x'
       this->x = x;
   }
   void print() { cout << "x = " << x << endl; }
};

以下是第二点和第三点的示例。

#include
using namespace std;
 
class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
  Test &setX(int a) { x = a; return *this; }
  Test &setY(int b) { y = b; return *this; }
  void print() { cout << "x = " << x << " y = " << y << endl; }
};
 
int main()
{
  Test obj1(5, 5);
 
  // Chained function calls.  All calls modify the same object
  // as the same object is returned by reference
  obj1.setX(10).setY(20);
 
  obj1.print();
  return 0;
}

这个问题的测验

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。