📜  C++ |运算符重载|问题9

📅  最后修改于: 2021-05-25 23:05:15             🧑  作者: Mango

#include
using namespace std;
  
class Point {
private:
  int x, y;
public:
  Point() : x(0), y(0) { }
  Point& operator()(int dx, int dy);
  void show() {cout << "x = " << x << ", y = " << y; }
};
  
Point& Point::operator()(int dx, int dy)
{
    x = dx;
    y = dy;
    return *this;
}
  
int main()
{
  Point pt;
  pt(3, 2);
  pt.show();
  return 0;
}

(A) x = 3,y = 2
(B)编译器错误
(C) x = 2,y = 3答案: (A)
说明:这是函数调用运算符重载的简单示例。

重载时,函数调用运算符不会修改函数的调用方式。相反,它修改了将运算符应用于给定类型的对象时应如何解释。
如果为类重载函数调用运算符,则其声明将具有以下形式:

return_type operator()(parameter_list) 

这个问题的测验

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