提问人:aurora 提问时间:5/8/2022 更新时间:5/8/2022 访问量:265
C++ 中的深度复制构造函数
Deep copy constructor in C++
问:
该程序旨在为 Foo 创建一个深度复制构造函数。下面是类定义:
class Foo {
int _cSize;
char *_cValues;
std::vector<int> _iValues;
double _dValues[100];
public:
double &dValues(int i) { return _dValues[i]; }
int &iValues(int i) { return _iValues[i]; }
char &cValues(int i) { return _cValues[i]; }
int cSize(void) const { return _cSize; }
Foo(void) : _cSize(100), _cValues(new char[_cSize]) {}
};
下面是复制构造函数的实现:
Foo &Foo::operator=(const Foo& foo) {
_cSize = foo._cSize;
_cValues = new char [_cSize];
for (int i = 0; i < _cSize; i++) {
_cValues[i] = foo._cValues[i];
}
_iValues = foo._iValues;
for (int i = 0; i < 100; i++) {
_dValues[i] = foo._dValues[i];
}
return *this;
}
但是,显示错误“隐式声明的复制赋值运算符的定义”。关于如何修复复制构造函数的任何建议?operator=
答:
0赞
Chris HazardXD
5/8/2022
#1
复制构造函数类似于
class Foo {
// ...
public:
Foo(const Foo& op) {
// copy fields
}
};
请注意,它们是构造函数,就像您声明的 Foo(void) 一样,但它们有一个参数是常量引用。
评论
operator=
std::string
std::vector<char>
operator=
_cValues