简体   繁体   中英

Deep copy constructor in C++

The program is aimed to create a deep copy constructor for Foo. Here's the class definition:

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". 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.

See also: Copy constructor and = operator overload in C++: is a common function possible?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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