c++ - 警告 : base class should be explictily initialized in the copy constructor

标签 c++ copy-constructor

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

我编写了一个 vector 类(以下称为 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];
            }
        }
    }

我做错了什么?

最佳答案

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

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

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

编辑:拥有私有(private)的会很方便

typedef Elements<Elements<T, N>, M> basetype;

在你的类定义中的某处。

关于c++ - 警告 : base class should be explictily initialized in the copy constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21139723/

相关文章:

c++ - 如何制作此构造函数的深拷贝?

c++ - 无法在简单程序中按下 QPushButton

c++ - 使用 QT + OpenCV 的多线程

c++ - 快速平面旋转算法?

c++复制初始化和直接初始化,奇怪的情况

c++ - 复制构造函数和析构函数八叉树c++

c++ - .c_str() 未按预期运行

c++ - 从模板类多重继承

c++ - 返回成员变量时,编译器是否进行返回值优化?

C++ 初始化指针/引用/复制的细微差别