I'm an intermediate C++ user and I encountered the following situation. The class definition shown below compiles fine with a g++ compiler. But I cannot put my finger on what exactly the whole syntax means.
My guess is that the function operator int()
returns an int
type.
Moreover, I cannot figure out how to use the overloaded operator ()
in main()
class A
{
public:
A(int n) { _num = n; } //constructor
operator int();
private:
int _num;
};
A::operator int() // Is this equivalent to "int A::operator()" ??
{
return _num;
}
int main()
{
int x = 10;
A objA(x); //creating & initializing
// how to use operator() ?
// int ret = objA(); // compiler error when uncommented
return 0;
}
Any help will be appreciated.
operator int()
is a conversion function that declares a user-defined conversion from A
to int
so that you can write code like
A a;
int x = a; // invokes operator int()
This is different from int operator()()
, which declares a function-call operator that takes no arguments and returns an int
. The function-call operator allows you to write code like
A a;
int x = a(); // invokes operator()()
Which one you want to use depends entirely on the behavior that you want to get. Note that conversion operators (eg, operator int()
) can get invoked at unexpected times and can cause pernicious errors.
you can use this one
#include <iostream>
using namespace std;
class A{
public:
A(int n) { _num=n;}
operator int();
private:
int _num;
};
A::operator int(){
return _num;
}
int main(){
A a(10);
cout<<a.operator int()<<endl;
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.