子类化并使用基类初始化器
我有这个:
class foo {
public:
int a;
int b;
int c;
};
这很好,但我想添加一些运算符重载而不修改类 foo:
class bar: public foo {
operator==(const bar &x) const {
return a == x.a;
}
}
到目前为止还好,但现在我需要使用从另一个类获得的对象数组来初始化 bar。没问题,我可以将所有 foo 变量复制到专用构造函数中的 bar 中:
bar::bar(foo &x) {
a = foo.a;
/* etc */
}
但这看起来很混乱,如果 foo 类 over 更新了,那么我也必须更新 bar 。如果 bar 可以自动初始化自己,那就更好了(它永远不会包含自己的数据成员)
I have this:
class foo {
public:
int a;
int b;
int c;
};
Which is fine, but I want to add some operator overloading without modifying class foo:
class bar: public foo {
operator==(const bar &x) const {
return a == x.a;
}
}
Fine so far, but now I need to initialise bar with an array of objects I get from another class. No problem, I can just copy all of the foo variables over to bar in a dedicated constructor:
bar::bar(foo &x) {
a = foo.a;
/* etc */
}
But this seems messy, and if class foo over gets updated, then I have to update bar too. Much preferable if bar could automatically initialise itself (it'll never contain its own data members)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是像确保 Foo 有一个复制构造函数那么简单吗……
isn't it as simple as making sure Foo has a copy constructor.......
嗯,很简单:
只需使用 foo 的复制构造函数即可。
:
和{
之间的所有内容都称为初始化列表。您可以直接在其中初始化您的成员和基类。对于 foo,复制构造函数可能如下所示:请注意,我通过 const 引用获取两个参数,这是一个很好的做法,因为您没有接触其他对象。另请注意,大多数情况下,您自己为
foo
编写复制构造函数是不必要的,只有当您的类包含原始指针时(例如int*
)。如果您没有定义复制构造函数而只是对所有数据成员进行浅表复制,则编译器将自行生成复制构造函数。Well, easy:
Just use
foo
's copy constructor. Everything between the:
and the{
is called the initializer list. You can directly initialize your members and base classes in there. Forfoo
, the copy constructor could look like the following:Note that I take both arguments by const reference, which is a good practice since you aren't touching the other objects. Also note that writing a copy constructor for
foo
yourself is not necessary most of the time, only when your class contains raw pointers (int*
for example). The compiler will generate a copy ctor itself if you don't define one and just make a shallow copy of all data members.继承构造函数在 C++03 中无法完成,但可以近似。添加这些构造函数:
在 C++0x 中,使用单个可变参数模板构造函数和完美转发。
Inheriting constructors can't be done in C++03, but can be approximated. Add these constructors:
In C++0x use a single variadic templated constructor and perfect forwarding.