简体   繁体   English

C++ 中的深拷贝构造函数

[英]Deep copy constructor in C++

The program is aimed to create a deep copy constructor for Foo.该程序旨在为 Foo 创建一个深拷贝构造函数。 Here's the class definition:这是 class 的定义:

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]) {}

};

and here's the implementation of copy constructor:这是复制构造函数的实现:

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;
}

However, the operator= is showing an error that "Definition of implicitly declared copy assignment operator".但是, operator=显示错误“隐式声明的复制赋值运算符的定义”。 Any suggestions on how to fix the copy constructor?关于如何修复复制构造函数的任何建议?

Copy constructors are like复制构造函数就像

class Foo {
  // ...

  public:
    Foo(const Foo& op) {
      // copy fields
    }
};

note that they are constructors just like Foo(void) you declared, but they have one param that's a const reference.请注意,它们就像您声明的 Foo(void) 一样是构造函数,但它们有一个参数,即 const 引用。

See also: Copy constructor and = operator overload in C++: is a common function possible?另请参阅: C++ 中的复制构造函数和 = 运算符重载:常见的 function 可能吗?

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

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