c++ - 可重用的构造函数 C++

标签 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;
}

我的问题是,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/

相关文章:

c# - 了解 C# 中的虚拟方法、方法隐藏和重写

c++ - 错误 C2248 : cannot access protected member declared in class

c++ - 修改 Windows 上的堆栈、TIB 和异常

c++ - 如何缩短声明命名常量的时间?

c++ - "inline"功能的用处

java - 找不到符号 = 新

java - 虽然构造函数需要参数我仍然可以在没有它们的情况下调用它

c++ - 在 "Effective Modern C++"示例中在索引运算符之前使用 std::forward 的原因

java - 为什么有些库会定义自己的集合?

php - 为什么在面向对象的 PHP 中不推荐直接访问属性?