【发布时间】:2015-02-05 06:18:19
【问题描述】:
我想知道为什么在 C++ 中不能将父类构造函数用于特定签名,以防派生类错过?
例如在下面的示例中,我无法用std::string 初始化dd 对象。
#include <iostream>
class Base
{
int num;
std::string s;
public:
Base(int _num){ num = _num;}
Base(std::string _s){ s = _s;}
};
class Derived : public Base {
public:
Derived(int _num):Base(_num){}
};
int main()
{
Base b(50);
Derived d(50);
Base bb("hell");
Derived dd("hell"); // <<== Error
return 0;
}
通过继承,我希望扩展一个类并且不会丢失以前的功能,但在这里我觉得丢失了一些。
在一个更实际的例子中,我创建了我的std::string 版本,但在某些情况下它的行为不像std::string:
#include <string>
#include <iostream>
class MyString: public std::string {
public:
void NewFeature(){/* new feature implementation*/}
};
int main()
{
MyString s("initialization"); // <<== Error: I expect to initialize with "..."
cout<<s; // <<== Error: I expect to print it like this.
return 0;
}
有人可以解释一下吗?
【问题讨论】:
标签: c++ inheritance constructor initialization