Computer >> Máy Tính >  >> Lập trình >> C ++

Ngăn sao chép đối tượng trong C ++

Trong C ++, khi các lớp được tạo, chúng ta có thể sao chép nó bằng cách sử dụng một số hàm tạo bản sao hoặc toán tử gán. Trong phần này, chúng ta sẽ thấy, làm thế nào để ngăn chặn bản sao đối tượng của một lớp trong C ++. Để ngăn chặn sao chép đối tượng, chúng ta có thể tuân theo một số quy tắc. Những thứ này giống như bên dưới.

1. Tạo phương thức khởi tạo bản sao riêng và toán tử gán riêng.

Ví dụ

#include <iostream>
using namespace std;
class MyClass {
   int x;
   public:
      MyClass() {
         //non-parameterized constructor
      }
      MyClass(int y): x(y) {
      }
   private:
      MyClass(const MyClass& obj) : x(obj.x) {
         //private copy constructor
      }
      MyClass& operator=(const MyClass& tmp_obj) {
         //private assignment operator (overloaded)
            x = tmp_obj.x;
         return *this;
      }
   };
 main() {
   MyClass ob(50);
   MyClass ob2(ob); // calls copy constructor
   ob2 = ob; // calls copy assignment operator
}

Đầu ra

[Error] 'MyClass::MyClass(const MyClass&)' is private
[Error] within this context
[Error] 'MyClass& MyClass::operator=(const MyClass&)' is private
[Error] within this context

2. Kế thừa lớp giả với hàm tạo bản sao riêng và toán tử gán riêng.

Ví dụ

#include <iostream>
using namespace std;
class DummyClass {
   public:
      DummyClass() {
      }
   private:
      DummyClass(const DummyClass& temp_obj) {
      }
      DummyClass& operator=(const DummyClass& temp_obj) {
      }
};
class MyClass : public DummyClass {
   int x;
   public:
      MyClass() { }
      MyClass(int y) : x(y) {
      }
};
int main() {
   MyClass ob1(50);
   MyClass ob2(ob1); // Calls copy constructor
   ob2 = ob1; // Calls copy assignment operator
}

Đầu ra

[Error] 'DummyClass::DummyClass(const DummyClass&)' is private
[Error] within this context
In function 'int main()':
[Note] synthesized method 'MyClass::MyClass(const MyClass&)' first
required here
In member function 'MyClass& MyClass::operator=(const MyClass&)':
[Error] 'DummyClass& DummyClass::operator=(const DummyClass&)' is
private
[Error] within this context
In function 'int main()':
[Note] synthesized method 'MyClass& MyClass::operator=(const
MyClass&)' first required here