2
我只是应该习惯基本的复制构造函数。没有匹配构造函数用于初始化
我假设我正确放置了拷贝构造函数。
但是,当我尝试编译,我不断收到错误“无匹配的构造函数B的初始化”
我有点困惑。
class A {
int valuea;
public:
A(const A&); // copy constructor
int getValuea() const { return valuea; }
void setValuea(int x) { valuea = x; }
};
class B : public A {
int valueb;
public:
B(int valueb);
B(const B&); // copy constructor
int getValueb() const { return valueb; }
void setValueb(int x) { valueb = x; }
};
int main() {
B b1;
b1.setValuea(5);
b1.setValueb(10);
B b2(b1);
cout << "b2.valuea=" << b2.getValuea() << "b2.valueb=" << b2.getValueb() << endl;
return 0;
}
对于A或B,没有默认构造函数 - 只要声明构造函数 - 编译器将不会生成默认构造函数。 –
如果给'valueb'参数一个默认值,'B(int)'构造函数可以作为'B'的默认构造函数,从而允许'B b1;'语句工作。然而,'A'没有构造函数可以调用'B'构造函数,所以'B'依然不能被构造。 –