2010-09-03 41 views
2

我是一名中级C++用户,遇到以下情况。下面显示的类定义可以用g ++编译器编译。但我不能把手指放在整个语法的意义上。
我的猜测是功能operator int()返回一个int类型。隐式转换运算符重载语法

而且,我无法弄清楚如何在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; 
} 

任何帮助将不胜感激使用重载operator()

+0

重载'运算符()'?什么重载'operator()'?你的代码没有任何重载的'operator()'。这就是为什么你不能使用它。 – AnT 2010-09-03 06:53:48

+0

是的。我非常误会关键字操作符把我带到其他地方。 – vthulhu 2010-09-03 07:15:12

+0

[此C++语法的含义是什么以及它为什么可以工作?]的可能的重复(http://stackoverflow.com/questions/3632746/what-does-this-c-syntax-mean-and-why-does-it工作) – sbi 2010-09-03 07:47:22

回答

7

operator int()转换函数声明一个用户定义的转换从Aint,这样就可以写出这样的代码

A a; 
int x = a; // invokes operator int() 

这不同于int operator()(),其声明了一个函数调用操作者没有参数并返回int。该函数调用运营商允许你编写代码就像

A a; 
int x = a(); // invokes operator()() 

哪一个要使用完全取决于你想要得到的行为。请注意,转换运算符(例如,operator int())可能会在意外时间调用,并可能导致有害的错误。

+0

谢谢!这是很酷的东西! – vthulhu 2010-09-03 06:37:56

+0

@vthulu: 你似乎是社区新人,所以只是为了您的信息,如果你对上述答案感到满意,你会想选择出现在这个答案旁边的勾号,这实质上意味着你接受答案 – mukeshkumar 2010-09-03 07:17:40

+2

“请注意,转换运算符(例如,运算符int())可能会在意外时间被调用,并可能导致有害的错误。”我会说这有点强:__远离他们!__ – sbi 2010-09-03 07:42:33

0

你可以使用这个

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

}