C + + operator overloading (8)-default assignment operator and reference __c++

Source: Internet
Author: User
Tags shallow copy

As we mentioned earlier, when there is no user-defined assignment operator, the compiler defaults to generating a shallow copy

If the pointer not only assigns the value to the point, it is also assigned to the address, which causes the problem

Does this question apply to the reference?

#include <iostream>
using namespace std;

Class Mytesttwo {
private:
	int value;
	int &ref = value;   Create a reference to value public
:
	mytesttwo (int i) {
		value = i;
		ref = value;
	}
	
	void Myprint () {
		cout << ref << Endl;
	}

	void SetValue (int i) {
		value = i;
	}
};


int main () {

	mytesttwo testa ();
	Mytesttwo Testb (a);

	Testa.myprint ();
	Testb.myprint ();

	Testb = Testa;  Prompt error
	
	system ("PAUSE");
	return 0;
}

This is not allowed, only the user can create the operator

mytesttwo& operator = (const mytesttwo& obj) {
		this->value = Obj.value;
		return *this;
	}

In the following cases, the compiler does not generate the default build operator

(1) Non-static data members in a class that contain const or volatile

(2) Non-static data members that cannot be assigned (such as references)

(3) An inherited base class cannot use an assignment operator (for example, a member of a reference type in a base class)

(4) The class contains pointers





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.