eve*_*sor 14 c++ oop constructor reusability
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;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,C++中有没有允许你这样做的语法?
Ben*_*igt 11
C++ 11添加了构造函数委托和构造函数继承.您需要获得支持它的编译器.
要继承构造函数,需要使用using声明:
class Base { ... };
class Derived : public Base
{
using Base::Base;
};
Run Code Online (Sandbox Code Playgroud)
要委托,使用ctor-initializer,但在同一个类中指定另一个构造函数,而不是任何子对象(所有基础和成员子对象将由委托给的构造函数初始化):
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
{}
};
Run Code Online (Sandbox Code Playgroud)
完美的转发也可以派上用场.
Cat*_*lus 11
其他人已经回答了关于C++ 11的问题,但对于C++ 03,有一种可能的解决方法:使用带有所需构造函数的基类.
struct foo_base {
foo_base(int a, int b, int c) : a(a), b(b), c(c) { }
int a, b, c;
};
struct foo : foo_base {
foo() : foo_base(0, 0, 0) { }
foo(const foo& other) : foo_base(other.a, other.b, other.c) { }
foo(int a, int b, int c) : foo_base(a, b, c) { }
};
Run Code Online (Sandbox Code Playgroud)
当然,您需要考虑是否值得为您的目的使用样板.