【发布时间】:2012-10-17 00:28:09
【问题描述】:
我只是应该习惯基本的复制构造函数。
我假设我正确放置了复制构造函数。
但是当我尝试编译时,我不断收到错误“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 都没有默认构造函数——一旦你声明了构造函数——编译器就不会生成默认构造函数。
-
B(int)构造函数可以充当B的默认构造函数,如果你给valueb参数一个默认值,从而允许B b1;语句工作。但是A没有B的构造函数可以调用的构造函数,所以B仍然根本无法构造。
标签: c++ copy-constructor