gpt4 book ai didi

具有非类型参数 : how to overload the assign operator? 的 C++ 模板类

转载 作者:行者123 更新时间:2023-11-28 04:57:43 27 4
gpt4 key购买 nike

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

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 次类测试对象,

我想重载赋值运算符来执行第二个操作。

我试过

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

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

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

谢谢!

最佳答案

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

// 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>

关于具有非类型参数 : how to overload the assign operator? 的 C++ 模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46801864/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com