重载括号 () 是否影响构造函数调用?
Does overloading parenthesis () effect constructor call?
我对 () 运算符重载几乎没有疑问。我的问题是:
- 重载括号()是否影响构造函数调用?
- 如果它会影响意味着我应该在 constructor/destructor 调用之前做一些 pre/post 处理吗?
- 如果问题 2 是可能的,则意味着我应该 pre/post 处理什么,不应该处理什么?
如果您觉得这与任何其他问题重复或提出此问题的方式不正确,则也请在此处发表评论。提前致谢....
不会干扰构造函数调用。原因是构造函数调用适用于 type 或 while 构造 instance,而 operator()
在 已经构造的实例 上工作。
示例:
struct A
{
A(int) {}
void operator()(int) {}
};
int main()
{
A(42); // calls the constructor A::A(int)
A a(42); // also calls A::A(int)
a(42); // calls A::operator(int)
}
问题:
Does overloading parenthesis () effect constructor call?
不,不是。 operator()
函数可以与对象一起使用。构造函数使用 class/struct 名称。示例:
struct Foo
{
Foo() {}
int operator()(){return 10;}
};
Foo foo = Foo(); // The constructor gets called.
foo(); // The operator() function gets called.
Foo foo2 = foo(); // Syntax error. Cannot use the return value of foo()
// to construct a Foo.
int i = foo(); // OK.
我对 () 运算符重载几乎没有疑问。我的问题是:
- 重载括号()是否影响构造函数调用?
- 如果它会影响意味着我应该在 constructor/destructor 调用之前做一些 pre/post 处理吗?
- 如果问题 2 是可能的,则意味着我应该 pre/post 处理什么,不应该处理什么?
如果您觉得这与任何其他问题重复或提出此问题的方式不正确,则也请在此处发表评论。提前致谢....
不会干扰构造函数调用。原因是构造函数调用适用于 type 或 while 构造 instance,而 operator()
在 已经构造的实例 上工作。
示例:
struct A
{
A(int) {}
void operator()(int) {}
};
int main()
{
A(42); // calls the constructor A::A(int)
A a(42); // also calls A::A(int)
a(42); // calls A::operator(int)
}
问题:
Does overloading parenthesis () effect constructor call?
不,不是。 operator()
函数可以与对象一起使用。构造函数使用 class/struct 名称。示例:
struct Foo
{
Foo() {}
int operator()(){return 10;}
};
Foo foo = Foo(); // The constructor gets called.
foo(); // The operator() function gets called.
Foo foo2 = foo(); // Syntax error. Cannot use the return value of foo()
// to construct a Foo.
int i = foo(); // OK.