OOP 的基石之一是重用代码,而不是一遍又一遍地重复。因此,您的项目会缩短并变得更具可读性。
C++ 为您提供了重用方法而不是重复代码所需的所有工具。虽然当涉及到构造函数时,我不知道如何重用它们。
我不是谈论遗产或如何向父亲传达信息。我说的是重用类本身的构造函数。
JAVA中的类比是这样的:
public Foo() {
this(0,0,0);//Not needed in this case, just to clarify
}
public Foo(Foo f){
this(f.getA(), f.getB(), f.getC());
}
public Foo(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
我的问题是,C++ 中是否有任何语法允许您这样做?
最佳答案
C++11 has added constructor delegation and constructor inheritance .
要继承构造函数,需要using-declaration:
class Base { ... };
class Derived : public Base
{
using Base::Base;
};
要委托(delegate),请使用 ctor-initializer,但在同一个类中指定另一个构造函数,而不是任何子对象(所有基子对象和成员子对象都将由委托(delegate)给的构造函数初始化):
class Another : public Base
{
int member;
Another(int x)
: Base(), member(x) // non-delegating constructor initializes sub-objects
{}
Another(void)
: Another(5) // delegates -- other constructor takes care of Base and member
{}
};
而且完美转发也能派上用场。
关于c++ - 可重用的构造函数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7667701/