输入输出运算符重载
#include <string>
#include <iostream>
using namespace std;
class Fruit;
ostream& operator <<(ostream& out, const Fruit& x);
istream& operator >>(istream& in, Fruit& x);
class Fruit {
public:
Fruit();
friend ostream& operator << (ostream& out, const Fruit& x);
friend istream& operator >> (istream& in, Fruit& x);
private:
string name, color;
};
#include <iostream>
#include "Fruit.h"
using namespace std;
Fruit::Fruit() {
name = "apple";
color = "green";
}
ostream& operator << ( ostream& out, const Fruit& x) {
out << "name: " << x.name << " color: " <<x.color << endl;
return out;
}
istream& operator >> (istream& in, Fruit& x) {
cout << "Please enter the name: " << endl;
in >> x.name;
cout << "Please enter the color: " << endl;
in >> x.color;
return in;
}
int main() {
Fruit fruit1;
cout << fruit1;
cin >> fruit1;
cout << fruit1;
cout << "Finished!" << endl;
}
重载前置++、后置++、前置–、后置–
class COMPLEX {
public: //complex.h
COMPLEX(double r = 0, double i = 0);
COMPLEX(const COMPLEX& other);
void print();
COMPLEX & operator++();
COMPLEX operator++(int);
COMPLEX & operator--();
COMPLEX operator--(int);
protected:
double real, image;
};
COMPLEX& COMPLEX::operator++() {
real += 1;
image += 1;
return *this;
}
COMPLEX COMPLEX::operator++(int) {
COMPLEX before = *this;
real += 1;
image += 1;
return before;
}
COMPLEX& COMPLEX::operator--() {
real -= 1;
image -= 1;
return *this;
}
COMPLEX COMPLEX::operator -- (int) {
COMPLEX before = *this;
real -= 1;
image -= 1;
return before;
}
重载运算符()
#include <iostream>
using namespace std;
class Matrix {
private
double v[3][3];
public:
Matrix(double [][3], int);
Matrix() {}
double& operator()(int, int);
};
Matrix::Matrix(double ve[][3], int r_size) {
if (r_size != 3)
out << " Error!!";
else
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
v[i][j] = ve[i][j];
}
double& Matrix::operator()(int i, int j) {
return v[i][j];
}
void main() {
double a[3][3];
int i, j;
for(i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
cin >> a[i][j];
Matrix M(a, 3);
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
cout << M(i, j) <<" ";
cout << endl;
}
}