【问题标题】:Constructing a parent object in a child class在子类中构造父对象
【发布时间】:2014-11-16 00:04:21
【问题描述】:

我有一个用于制作复杂矩阵的继承类(来自父矩阵类)。这个想法是从父类为矩阵的真实和复杂部分创建两个对象。我对如何制作构造函数有点困惑。代码是:

template <class type>
class complexMatrix: public matrix<type> 
{
public:

  matrix<type> Real;
  matrix<type> Complex;

  complexMatrix() //Default Constructor
  {
    matrix<type> Real;// Call the matrix class constructor by default
    matrix<type> Complex;
  }
  complexMatrix(int rows,int columns, string name) //Creat a complex matrix
  {
    string name_real,name_complex;
    name_real = name;
    name_complex = "i"+name;
    matrix<type> Complex(rows,columns,name_complex); // Create Imaginary matrix
    matrix<type> Real(rows,columns,name_real);
  }
  void complexrandomize()
  {
    Real.matrix<type>::randomize();
    Complex.matrix<type>::randomize();
  }

};

这段代码显然不起作用。在我找到here on stackoverflow 的答案中,我了解到我可以从父对象初始化两个对象,然后使用 Real(rows,columns,name) 调用它。然而,就我而言,这不起作用,因为我需要 () 运算符被重载。所以这个解决方案是不可能的。我能想到的另一个解决方案是在构造函数中创建对象 Real 和 Complex 并手动复制 Real 和 Complex 成员对象中的所有值。不知何故,这听起来不是一个很好的解决方案。

有没有人有更好的方法来解决这个问题?

【问题讨论】:

  • 你能解释一下如何做吗?我不熟悉初始化列表。
  • 您的代码需要使用成员初始化列表,因为您的类正在尝试调用其数据成员的构造函数。因此,在默认构造函数中,您需要complexMatrix() : Real(), Complex() {},它将调用您的两个数据成员的默认构造函数。至于第二个构造函数,它将是complexMatrix(…) : Real(rows, columns, name), Complex(rows, columns, "i"+name) {}

标签: c++ class inheritance operator-overloading


【解决方案1】:

使用初始化列表:有关详细信息,请参阅 here

template <class type>
class complexMatrix: public matrix<type> 
{
public:

  matrix<type> Real;
  matrix<type> Complex;

  complexMatrix() : Real(),Complex() // Call the matrix class constructor by default
  {
  }
};

【讨论】:

  • 如果他= default'ed构造函数会更好。
  • 我同意这种情况,但我们不知道他是否使用了 C++11 编译器。此外,如果他想用默认构造函数做一些重要的事情,他不能=default 构造函数。仅出于学习初始化列表的目的,我认为这个答案就足够了。
  • 我试过了,效果很好。我想我正在使用 C++11 编译器,虽然我不太确定如何检查我的 g++。非常感谢。如果不是这样,还有其他方法吗?我还尝试创建一个指向对象的指针,然后将其初始化为从父类构造的对象的地址。 Valgrind 开始表现得很奇怪,我放弃了这条路。
  • 你可以写complexMatrix() = default;它会为你创建构造函数,只需删除我上面写的整个构造函数并用它替换它。但是,如果你想让你的构造函数做一些不平凡的事情,你不能使用=default;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
  • 2023-03-27
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
相关资源
最近更新 更多