Kel*_* Lu 5 c++ constructor overloading function call
假设我定义,实例化并使用加法器仿函数,如下所示:
class SomeAdder {
public:
SomeAdder(int init_x): x(init_x) {}
void operator()(int num) { cout << x + num <<endl; }
private:
int x;
};
SomeAdder a = SomeAdder (3);
a(5); //Prints 8
SomeAdder b(5);
b(5); //Prints 10
Run Code Online (Sandbox Code Playgroud)
构造函数和重载()运算符都使用双括号调用,并具有相同类型的参数.在实例化SomeAdder和"函数调用" 期间,编译器如何确定使用哪个函数来实现正确的行为?答案似乎表面上很明显,但我无法绕过这个想法.
谢谢你的时间!
您的示例比较了重载的构造函数和成员函数operator()。编译器知道调用哪一个以及何时调用。这非常简单:
当要构造一个对象时,就会调用构造函数。
在已构造的对象上调用成员函数。在你的例子中,成员函数是operator().
这意味着,它们是在完全不同的上下文中调用的。没有歧义,没有混乱。