简体   繁体   中英

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:

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()"

You accidentally implemented a type conversion operator and not operator() . Overload operator() like this instead (I removed the return value because you discard it in main anyway):

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM