警告:应该在复制构造函数中明确初始化基类

时间:2014-01-15 14:14:22

标签: c++ copy-constructor

我正在为CUDA处理编写矩阵类。

我编写了一个矢量类(以下称为Elements)并将其用于矩阵基础。

以下是模板定义:

template <typename T, std::size_t M, std::size_t N>
class Matrix : public Elements< Elements< T, N >, M > {

}

应该注意的是,Elements类和Matrix类中没有动态分配任何内容。

我在复制构造函数中收到warning: base class ‘struct Elements<Elements<double, 2ul>, 2ul>’ should be explicitly initialized in the copy constructor警告。这是复制构造函数:

    DEVICE HOST
    Matrix(const Matrix & that) {
        for (std::size_t ind = 0; ind < M; ind++) {
            for (std::size_t jnd = 0; jnd < N; jnd++) {
                (*this)[ind][jnd] = that[ind][jnd];
            }
        }
    }

我做错了什么?

3 个答案:

答案 0 :(得分:5)

您没有在复制构造函数中初始化基类。试试这个:

Matrix(const Matrix & that) : Elements<Elements<T, N>, M>(that) {
    /* ... */
}

派生类'复制构造函数的初始化列表应该包含对基类'复制构造函数的显式调用,就像所有其他构造函数一样,否则,基类将默认初始化。

修改:私有

非常方便
typedef Elements<Elements<T, N>, M> basetype;

在你的班级定义中。

答案 1 :(得分:0)

如果明确定义派生类的复制构造函数并且不在ctor列表中调用基类的复制构造函数,则编译器本身将调用基类的默认构造函数。它可能不是你想要的。所以编译器警告你。

我有一个例子来证明我的艺术作品的不同之处 "Implicitly defined copy constructor and explicitly defined copy constructor: what is the difference" 它是用俄语写的,但你可以使用谷歌服务翻译来阅读它。

答案 2 :(得分:0)

对于任何派生类,只要派生类是,就需要构造基类。如果您的基类没有默认(0参数)构造函数,则必须指定如何在所有派生类的构造函数中构造它。

因此,假设Elements有一个公共拷贝构造函数,你需要这样的东西:

Matrix(const Matrix & that) 
: Elements<Elements<T, N>, M>(that)
{ 
  ...
}