[英]Why can't I call operator()?
I am trying to understand different topics in C++ by examples and I cannot get this example to work: 我试图通过示例理解C ++中的不同主题,但无法使该示例正常工作:
template<typename T>
class zero_init
{
T val;
public:
zero_init() : val(static_cast<T>(0)) { std::cout << "In constructor with no parameters\n"; }
operator T() const { std::cout << "In operator T()\n"; return val; }
};
int main()
{
const zero_init<int> x;
x(); //Error!
return 0;
}
I am obviously trying to call the operator() but it gives the error: "call of an object of a class type without appropriate operator()" 我显然正在尝试调用operator(),但它给出了错误:“在没有适当的operator()的情况下调用类类型的对象”
You accidentally implemented a type conversion operator and not operator()
. 您不小心实现了类型转换运算符,而不是operator()
。 Overload operator()
like this instead (I removed the return value because you discard it in main
anyway): 像这样重载operator()
(我删除了返回值,因为无论如何您都将其丢弃在main
):
#include <iostream>
template<typename T>
class zero_init
{
T val;
public:
zero_init() : val(static_cast<T>(0)) { std::cout << "In constructor with no parameters\n"; }
void operator()() const { std::cout << "In operator()\n"; }
};
int main()
{
const zero_init<int> x;
x();
return 0;
}
If you actually need the return value, do it like this: 如果您确实需要返回值,请按照以下步骤操作:
#include <iostream>
template<typename T>
class zero_init
{
T val;
public:
zero_init() : val(static_cast<T>(0)) { std::cout << "In constructor with no parameters\n"; }
T operator()() const { std::cout << "In operator()\n"; return val; }
};
int main()
{
const zero_init<int> x;
auto val = x();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.