2013-03-14 42 views
2

请看看这个程序,它生成错误:无效的用户定义的转换

#include <iostream> 
using namespace std; 
    class A 
    { 
    public: 

     virtual void f(){} 
     int i; 
    }; 

    class B : public A 
    { 
    public: 
     B(int i_){i = i_;} //needed 
     B(){}    //needed 
     void f(){} 
    }; 

    int main() 
    { 

     //these two lines are fixed(needed) 
     B b; 
     A & a = b; 

     //Assignment 1 works 
     B b1(2); 
     b = b1; 

     //But Assignment 2 doesn't works 
     B b2(); 
     b = b2; // <-- error 
    } 

在编译时,我得到以下错误:

$ g++ inher2.cpp 
inher2.cpp: In function ‘int main()’: 
inher2.cpp:32:10: error: invalid user-defined conversion from ‘B()’ to ‘const B&’ [-fpermissive] 
inher2.cpp:14:6: note: candidate is: B::B(int) <near match> 
inher2.cpp:14:6: note: no known conversion for argument 1 from ‘B()’ to ‘int’ 
inher2.cpp:32:10: error: invalid conversion from ‘B (*)()’ to ‘int’ [-fpermissive] 
inher2.cpp:14:6: error: initializing argument 1 of ‘B::B(int)’ [-fpermissive] 

你能帮我找到问题?谢谢

+0

当你需要它时,最令人头痛的解析问题在哪里? – chris 2013-03-14 06:17:34

+0

@chris首先,我以为你是在开玩笑,直到我看到答案:)烦人!... :)谢谢 – rahman 2013-03-14 06:23:14

回答

5

你的“B b2();”是C的“伤脑筋的解析”问题++(see here - 的“最棘手的解析”拍摄暧昧语法进一步)。

它看起来像C++编译器,你正在声明一个函数(预先声明)。

检查出来:

int foo(); //A function named 'foo' that takes zero parameters and returns an int. 

B b2(); //A function named 'b2' that takes zero parameters and returns a 'B'. 

当你以后做:

b = b2; 

它看起来像你想分配功能(B2)给一个变量(b) 。 调用构造零个参数,调用它不使用括号,你会被罚款:

B b2; 

欲了解更多信息,请参见:

+2

这不是“最”令人烦恼的解析。这只是令人烦恼的解析! – Nawaz 2013-03-14 06:18:23

+0

糟糕,你是对的。 – 2013-03-14 06:22:35

+0

@Nawaz你是什么意思:)他链接到维基百科的标题说这是“最”令人烦恼! – rahman 2013-03-14 06:25:08

2
B b2(); 

这是一个函数声明,变量声明!

函数名称是b2,它不带参数,并返回B类型的对象。

在C++中搜索令人头痛的解析