请查看该程序及其产生的错误:
#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]
你能帮我找到问题吗?谢谢
最佳答案
您的“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;
有关更多信息,请参见: