The overloads of the operators have some rules:
1. Overloaded operators must have either a class type or an enumeration type operand. This rule enforces that overloaded operators cannot redefine the meaning of the operators used for built-in type objects.
such as: int operator+ (int, int), can not
2. When designing overloaded operators for classes, you must choose whether to set the operator as a class member or as a normal, non-member function. In some cases, the program has no choice, the operator must be a member, and in other cases some experience can guide us in making a decision. Here are some guidelines:
A. Assignment (=), subscript ([]), operators such as Call (()) and member access Arrows (->) must be defined as members, and these operators are defined as non-member functions that are marked as errors at compile time.
B. Like assignment, a compound assignment operator should generally be defined as a member of a class. Unlike assignment, you do not have to do this, and if you define a non-member compound assignment operator, there is no compilation error.
C. Other operators that change the state of an object or are closely associated with a given type, such as self-increasing, self-subtraction, and reconciliation references, are typically defined as class members.
D-symmetric operators, such as arithmetic operators, equality operators, relational operators, and bitwise operators, are best defined as ordinary, non-member functions.
The e IO operator must be defined as a non member function, overloaded as a friend of the class.
Copy Code code as follows:
OverloadCinCout.cpp: Defines the entry point for a 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); Input output stream overload, not a member of a class,
Friend istream& operator >> (istream& is, fruit& f); So it should be declared as a friend function 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;
}