【发布时间】: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