C + + Primer Note 10_ operator Overloading _ assignment Operator _ Enter/output operator

Source: Internet
Author: User

1. Ode value operator

First, the value operator introduces the operator overloads to be said later. The previous section describes constructors, copy constructors, and a class that wants better control. You need to define your own constructors, copy constructors, destructors, and, of course, assignment operators . The three functions commonly referred to are copy, assignment, and destruction .

Suppose a class does not define its own assignment operator. Generates a default assignment operation on its own. This default assignment operation satisfies the requirements of the General class. It implements a shallow copy. However, when the function and function of the class are gradually intact, there are many problems. Therefore, it is necessary to control the behavior of the class by defining the assignment operator itself. Overloaded assignment operator functions are called when an assignment (=) operation occurs between an object of a class and an object .


Or a sample of the above section. Look at the code:

#include <iostream> #include <new> #include <string>using namespace Std;class Person{public:person () ; person (int n, const string &str); Person (const person &n); Person &operator= (const person &AMP;P);//assignment operator function ~person ();p rivate:int age;string *name;}; Person::P Erson (): Age (0), name (NULL) {cout << ' Default person ' << Endl;} Person::P Erson (int n, const string &str): Age (N), name (new string (str)) {cout << ' Init person ' << Endl;} Person::P Erson (const person &n) {if (n.name) {name = new string (* (N.name)), age = N.age;} Else{name = Null;age = 0;}} Person & person::operator= (const person &p) {if (this = = &p) {return *this;//infers whether the incoming object is the current object itself}string *tmp = new String (*p.name);//Allocate a space again delete this->name;//release the original space this->name = Tmp;this->age = P.age;return *this;} Person::~person () {cout << ' ~person ' << ' name: ' << name << ' Age: ' << age << endl;de Lete name;} int main () {person P1 ("SCOTT"); Person P2;p2 = P1;return 0;} 

Here, assuming that you do not define the assignment operator yourself, there is no error when executing P2 = P1. The error is in the destruction section and the reason is explained in the previous article.

Init person
Default person
~person name:0x8264020 age:20
~person name:0x8264020 age:20
Segmentation fault (core dumped)--segment Error!


After you define the assignment operator. The results of the execution are as follows:

Init person
Default person
~person name:0x8121030 age:20
~person name:0x8121020 age:20


Attention:

1) in general, most assignment operator functions combine the work of destructors and copy constructors .

2) Let's say that an object is given to itself. The assignment operator must work correctly.

3) When writing an assignment operator function. A good pattern is to copy the right-side object into a local temporary object. Once the copy is complete, it is safe to destroy the existing members of the left side object.

The data is then copied from the temporary object to the left side object.


2. Operator overloading

Above is an instance of a number of operator overloads. Overloaded operators are functions with special names: their names are made up of keywordoperator and the operation symbols to be defined later.

It also has a return value, a list of references, and a function body, just like a normal function.

Overloaded operator functions have as many number of operands as the operators do. A unary operator has a parameter. There are two binary operators.

For a two-tuple operator, the left-hand operand is passed to the first parameter, and the right-side operand is passed to the second parameter.

assuming that an operator function is a member function, its first (left-hand) operand is bound to the implicit this pointer. Therefore, the member operator function has fewer parameters than the operator's operand . (as in the previous example = operator)


2.1 Input and output operators

The IO standard libraries use >> and << to run input and output operations, respectively.

Class is able to define input and output operators as needed.

Examples:

#include <iostream> #include <new> #include <string>using namespace Std;class Person{public:person () ; person (int n, const string &str); Person (const person &n); Person &operator= (const person &p); ~person (); string GetName () const;friend ostream &operator<< ( Ostream &out, const person &AMP;P);//output operator friend IStream &operator>> (IStream &in, person &p);// Input operator Private:int age;string *name;}; Person::P Erson (): Age (0), name (NULL) {cout << ' Default person ' << Endl;} Person::P Erson (int n, const string &str): Age (N), name (new string (str)) {cout << ' Init person ' << Endl;} Person::P Erson (const person &n) {if (n.name) {name = new string (* (N.name)), age = N.age;} Else{name = Null;age = 0;}} Person & person::operator= (const person &p) {if (this = = &p) {return *this;}  String *tmp = new String (*p.name);d elete this->name;this->name = tmp;this->age = P.age;cout << "operator =" << Endl;return *this;} PErson::~person () {cout << ' ~person ' << ' name: ' << name << ' Age: ' << age << Endl;del Ete name;} String Person::getname () const{if (name) {return *name;} return string ();} Overloaded output operator Ostream &operator<< (ostream &out, const person &p) {out << "p.age:" << p.age <& Lt ", P.name:" << p.getname (); return out;} Overloaded input operator IStream &operator>> (IStream &in, person &p) {string s;cout << ' please input age and name: "; in >> p.age >> s;if (in)//infer if read correctly {p.name = new string (s);} Else{p = person ();} return in;} int main () {person P1 ("SCOTT"); Person P2 ("Kate"); Person P3;/*cout << p1 << endl;cout << p2 << endl;cout << p3 << endl;*/cin >> P3 ; cout << P3 << endl;return 0;}


Execute the program, input Mike, the results such as the following:

Init person
Init person
Default person
Please input age and Name:12 Mike
P.age:12, P.name:mike
~person name:0x939a088 Age:12
~person name:0x939a048 Age:10
~person name:0x939a020 age:20


Summarize:

1. The input and output operators must be non-member functions.

2. Input and output operators are generally declared as friend types.

3. The second parameter in the output operator function can be declared as const, since it does not need to change its value. The second parameter of the input operator cannot be a const because it accepts input. In addition, the return value is best referenced, avoiding the value copy process.




Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

C + + Primer Note 10_ operator Overloading _ assignment Operator _ Enter/output operator

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.