【问题标题】:C++ template class with argument copy constructor带有参数复制构造函数的 C++ 模板类
【发布时间】:2015-06-17 06:01:54
【问题描述】:

我有一个如下所示的 c++ 泛型类:

template <class T, int N> class TwoDimArray{
    private:
        T tda_[N][N];
        int n_;
    public:
        TwoDimArray(T tda[][N]){
           ..
        }
        ~TwoDimArray(){
           ..
        }
        ..
}

我将如何编写一个可以像这样调用的复制构造函数:

int a1[][2] = { 1, 2, 3, 4 };
TwoDimArray <int, 2> tdm1(a1);
TwoDimArray tdm1Copy (tmd1); // or whatever the correct form is

我希望我是清楚的。

【问题讨论】:

    标签: c++ templates copy-constructor


    【解决方案1】:

    你的代码中有很多错别字,但声明一个复制构造函数很简单:

    TwoDimArray(const TwoDimArray& rhs){/*implement it here*/}
    

    复制构造函数是模板类的一部分,所以复制时必须指定模板类型

    TwoDimArray<int, 2> tdm1Copy (tdm1); // specify <int,2> as the type
    

    或使用auto

    auto tdm1Copy(tdm2);
    

    下面的完整工作示例:

    #include <iostream>
    
    template <class T, int N> class TwoDimArray {
    private:
        T tda_[N][N];
        int n_;
    public:
        TwoDimArray(T tda[][N]) {
            // implement
        }
        ~TwoDimArray() {
            // implement
        }
        TwoDimArray(const TwoDimArray& rhs) // don't really need this
        {
            // implement
        }
    };
    
    int main()
    {
        int a1[][2] = { 1, 2, 3, 4 };
        TwoDimArray <int, 2> tdm1(a1);
        TwoDimArray<int, 2> tdm1Copy (tdm1); // specify <int,2> as the type
    }
    

    除非您是出于家庭作业或学习目的而这样做,否则只需使用 std::vector&lt;std::vector&lt;T&gt;&gt; 来“模拟”一个二维数组。


    补充说明:由于您的类包含一个数组(而不是指针,它们不一样),因此您不需要复制构造函数。默认的复制构造函数会为您执行此操作,即逐个元素复制数组元素。因此,只需完全摆脱复制构造函数,让编译器生成一个默认构造函数。

    【讨论】:

    • 你能帮忙实现这两个变量吗?我这样做是这样的:'TwoDimArray(const TwoDimArray& rhs) : tda_(rhs.tda_), n_(rhs.n_){ }' 但我得到“:无法为数组指定显式初始化程序”对不起错别字,我试图重构..是的,'作业目的'..
    • 您不能将一个数组分配给另一个数组。由于您的类包含一个数组(而不是指针,它们不一样),因此您不需要复制 ctor。默认的复制 ctor 会为您执行此操作,即逐个元素复制数组元素。因此,只需完全摆脱复制 ctor,让编译器生成一个默认值。
    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2019-10-04
    相关资源
    最近更新 更多