In depth analysis of C++ I and o operator overloading

  • 2020-04-02 00:58:55
  • OfStack

There are some rules for overloading operators:
An overloaded operator must have a class type or an enumeration type operand. This rule forces the overloading operator not to redefine the meaning of the operator used for a built-in type object.
Int operator+ (int, int), no      
2. When designing an overloaded operator for a class, you must choose whether to set the operator to a class member or to a normal nonmember function. In some cases, the program has no options and the operator must be a member. In other cases, some experience can guide our decisions. Here are some guidelines:
A. Assignment (=), subscript ([]), call (()), and member access arrow (-) > Operators such as) must be defined as members, and defining these operators as non-member functions will be marked as errors at compile time.
B. Like assignment, the compound assignment operator should normally be defined as a member of a class. Unlike assignment, you don't have to do this, and if you define it as a non-member compound assignment operator, there are no compilation errors.
C. Other operators that change object state or are closely related to a given type, such as self - increment, self - decrement and unreference, should usually be defined as class members.
D symmetric operators, such as arithmetic operators, equality operators, relational operators, and bit operators, are best defined as ordinary non-member functions.
The e IO operator must be defined as a non-member function and overridden as a friend of the class.

//Overloadcincout.cpp: defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
class Fruit
{
public:
 Fruit(const string &nst = "apple", const string &cst = "green"):name(nst),colour(cst){}
 ~Fruit(){}
 friend ostream& operator << (ostream& os, const Fruit& f);  //I/o stream overload, not a member of the class,
 friend istream& operator >> (istream& is, Fruit& f);       //So it should be declared as a friend of the class
private:
    string name;
 string colour;
};
ostream& operator << (ostream& os, const Fruit& f)
{
 os << "The name is " << f.name << ". The colour is " << f.colour << endl;
 return os;
}
istream& operator >> (istream& is, Fruit& f) 
{
 is >> f.name >> f.colour;
 if (!is)
 {
  cerr << "Wrong input!" << endl;
 }
 return is;
}
int _tmain(int argc, _TCHAR* argv[])
{
 Fruit apple;
 cout << "Input the name and colour of a kind of fruit." << endl;
 cin >> apple;      
 cout << apple;
 return 0;
}


Related articles: