繁体   English   中英

具有非类型参数的C ++模板类:如何重载Assign运算符?

[英]C++ template class with non-type parameter: how to overload the assign operator?

我正在写一个带有非类型参数的模板类

class Test
{   
public:
    Test() { std::cout << "Test::Test()" << std::endl; }

    Test(Test const&) { std::cout << "Test::Test(Test const&)" << std::endl; }

     ~Test() { std::cout << "Test::~Test()" << std::endl; }

     Test& operator=(Test const&)
     {
           std::cout << "Test& Test::operator=(Test const&)" << std::endl;
           return *this;
     }

     void print() const { std::cout << "Test::print() const" << std::endl; }
     void print() { std::cout << "Test::print()" << std::endl; }
};

上面是我的“测试”类,用于测试我的模板类和

template <typename T, unsigned int n>
class Array
{
private:
    T* value;
public:
    Array() {
        this->value = new T[n];
    }

    ~Array() {
        delete[] this->value;
    }

    Array* operator=(const Array* arr)
    {
        this->value = arr->value;
        return this->value;
    }

    T& operator[](int a) {
        return this->value[a];
    }

    unsigned int size()
    {
        return n;
    }
};

上面是我的带有非类型参数的模板类。

int main(int, char*[])
{
 /*first*/   Array<Test, 3> arr_1;

 /*second*/  Array<Test, 3> arr_3 = arr_1;

 return 0;
}

在我的main.cpp文件中

我用第一个使类测试对象3次,

我想重载assign运算符来执行第二个运算符。

我尝试过

Array* operator=(const Array* arr)
{
    this->value = arr->value;
    return this->value;
}

但是在无限次调用析构函数之后,它会“出现段错误”。

我想知道在这种情况下如何编写assign运算符重载。

谢谢!

要实现复制,您需要这样的东西:

// Copy constructor. When you write Array b = a, the compiler actually calls this, not operator=
Array( const Array& src )
{
    this->value = new T[ n ];
    std::copy_n( src.value, n, value );
}
Array& operator=( const Array& src )
{
    // No need for new[], operator= is called after the object is already constructed.
    std::copy_n( src.value, n, value );
    return *this;
}

但是,您不应该重新发明轮子。 C ++标准库中已经有不错的模板类。 如果您的数组很小(例如3),请使用std::array<Test, 3> 如果您的数组很大,并且希望将其保留在堆栈之外,则可以使用std::unique_ptr<std::array<Test, 3>>std::vector<Test>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM