gpt4 book ai didi

c++ - 从赋值运算符函数调用复制构造函数

转载 作者:可可西里 更新时间:2023-11-01 14:53:10 25 4
gpt4 key购买 nike

我有一个指向动态分配数组的类,所以我创建了复制构造函数和赋值运算符函数。由于复制构造函数和赋值运算符函数执行相同的工作,我从赋值运算符函数调用复制构造函数但得到 “错误 C2082:形式参数的重新定义”。我正在使用 Visual Studio 2012。

// default constructor
FeatureValue::FeatureValue()
{
m_value = NULL;
}

// copy constructor
FeatureValue::FeatureValue(const FeatureValue& other)
{
m_size = other.m_size;
delete[] m_value;
m_value = new uint8_t[m_size];

for (int i = 0; i < m_size; i++)
{
m_value[i] = other.m_value[i];
}
}

// assignment operator function
FeatureValue& FeatureValue::operator=(const FeatureValue& other)
{
FeatureValue(other); // error C2082: redefinition of formal parameter
return *this;
}

最佳答案

违规行不是您认为的那样。它实际上声明了一个FeatureValue 类型的变量other。这是因为构造函数没有名字,不能直接调用。

只要运算符未声明为虚拟,您就可以从构造函数中安全地调用复制赋值运算符。

FeatureValue::FeatureValue(const FeatureValue& other)
: m_value(nullptr), m_size(0)
{
*this = other;
}

// assignment operator function
FeatureValue& FeatureValue::operator=(const FeatureValue& other)
{
if(this != &other)
{
// copy data first. Use std::unique_ptr if possible
// avoids destroying our data if an exception occurs
uint8_t* value = new uint8_t[other.m_size];
int size = other.m_size;

for (int i = 0; i < other.m_size; i++)
{
value[i] = other.m_value[i];
}

// Assign values
delete[] m_value;
m_value = value;
m_size = size;
}
return *this;
}

这将非常有效,或者您可以使用 Vaughn Cato's answer 中建议的 copy-and-swap 习语的典型指南。

关于c++ - 从赋值运算符函数调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17480396/

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