c++ - 什么是在 C++ 中重载构造函数的正确而优雅的方法

标签 c++ c++11 inheritance constructor overloading

我在几年前接触过 C++,现在为了我正在从事的项目不得不重新使用它。我学习了大部分基础知识,但从未真正确定 C++ 希望您如何实现其类的概念。

我有使用 Java、Python 和 C# 等其他语言的经验。

我遇到的一个麻烦是理解如何在 C++ 中重载构造函数以及如何正确地进行继承。

例如,假设我有一个名为 Rect 的类和一个继承自 Rect 的名为 Square 的类。

在 Java 中...

public class Rect {
   protected double m_length, m_width;

   public Rect(double length, double width) {
      this.m_length = length;
      this.m_width = width;
   }

   public double Area()
   {
      return (this.m_length * this.m_width);
   }

}

public class Square extends Rect {
   private String m_label, m_owner;
   public Square(double side) {
      super(side, side);
      this.m_owner = "me";
      this.m_label = "square";
   }

   //Make the default a unit square
   public Square() {
      this(1.0);
      this.m_label = "unit square";
   }
}

然而,在 C++ 中,同样的过程让人感觉很复杂。

标题:

class Rect
{
public:
   Rect(double length, double width) : _length(length), _width(width) { } 
   double Area();

protected:
   double _length, _width;
}

class Square : public Rect 
{
public:
   Square(double side) : 
   Rect(side, side), _owner("me"), _label("square") { }

   Square() : Rect(1.0, 1.0), _owner("me"), _label("unit square");

private:
   std::string _owner, _label;
}

我觉得我不应该再写出 Rect 了。这看起来像是大量的重写,特别是因为在我的项目中我经常使用矩阵并且我希望构造函数能够像在 Java 中一样相互扩展以避免重写大量代码。

我确信有一种方法可以正确地做到这一点,但我还没有看到有人真正谈论过这个问题。

最佳答案

如果我正确理解了你的问题,那么如果两个构造函数中的字符串初始化器相同,那么你可以使用委托(delegate)构造函数

   explicit Square(double side) : 
   Rect(side, side), _owner("me"), _label("square") { }

   Square() : Square(1.0) {}

你也可以添加默认参数,例如

   explicit Square(double side, const char *owner = "me", const char *label = "square" ) : 
   Rect(side, side), _owner(owner), _label(label ) { }

   Square() : Square(1.0, "me", "unit square" ) {}

关于c++ - 什么是在 C++ 中重载构造函数的正确而优雅的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57295770/

相关文章:

c++ - 在代码的不同部分获取访问冲突错误

java - Java 中的隐式继承

c++ - 找不到命名空间,尽管它就在那里

c++ - 在不传递所有权的情况下重新分配函数中的智能指针?

c++ - CUDA 从单独的文件调用设备函数(名称修改?)

c++ - 找出函数、lambda 或函数的返回类型

c++ - 带有 lambda 捕获的 EXC_BAD_ACCESS

c++ - 模板化功能设计以实现可扩展性

C++类中的类方法继承

c++ - 为什么可以跳入不带初始值设定项的标量类型对象的范围?