我在下面有两个简单的类,一个是基类,另一个是从它派生的。
在派生类中有两个构造函数,一个接受基类和派生类所需的所有参数,另一个接受基类引用本身作为参数。
我知道将基类引用作为参数的构造函数不是一个好习惯。
但是,我想知道为什么它不被认为是一种好的做法?
它实现了与其他构造函数相同的功能。
有人可以澄清为什么这不是一个好的 OOP 实践吗?
class Base
{
public:
Base(int a, int b):
m_a(a),
m_b(b)
{}
Base(const Base& b):
m_a(b.m_a),
m_b(b.m_b)
{}
~Base() {}
protected:
int m_a;
int m_b;
};
class Derived : public Base
{
public:
// Constructor which takes base class argument and initializes base
Derived(Base &base, int c):
Base(base),
m_c(c)
{}
Derived(int a, int b, int c):
Base(a, b),
m_c(c)
{}
~Derived() {}
private:
int m_c;
};
int main()
{
Base base(1,2);
Derived derived1(base, 3); //
Derived derived2(1,2, 3);
}
最佳答案
有必要知道您指定第一个 Derived 构造函数的上下文。
但是,用const Base
参数定义它也许会更优雅。像这样的东西:
Derived(const Base &base, int c):
Base(base),
m_c(c)
{}
因此,它告诉编译器保护base
对象的状态。
此外,如果您使用的是 c++-11,那么您可能有兴趣声明:
using Base::Base;
在 Derived
类中,Derived
继承了 Base
的构造函数。因此,您可以在 main()
中添加:
Derived derived3(1,2);
那将完美编译。
在 c++-11 中,您还可以为 m_c
数据成员设置一个默认值。例如
int m_c = 0;
因此从 Base
继承的构造函数将使 Derived
处于一致状态
关于c++ - 以基类作为参数的派生类构造函数(这是好的做法吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27032321/