一:<<&>>重载(最好全局定义)
注意:在重载函数中如果形参位置颠倒,会出现:p<<cout这种情况
//全局模式(注意<<&>>最好全局)
class person {
public:
string name;
int age;
person(string name, int age) :name(name), age(age) {};
};
ostream& operator<<(ostream& out, const person& p)
{
out << "姓名:" << p.name << " 年龄:" << p.age;
return out;
}
//注意!!!在>>中,不要带const(自己好好想想我们cin是干嘛的)
istream& operator>>(istream& ci,person& p)
{
ci >> p.name>> p.age;
return ci;
}
int main()
{
person p("code out the future",1);
cin >> p;
cout << p;
return 0;
}
类内实现
class person {
public:
string name;
int age;
person(string name, int age) :name(name), age(age) {};
ostream& operator<<(ostream& out) //隐式调用,第一个形参是对象,第二个是重载
{
out << "姓名:" << this->name << " 年龄:" << this->age;
return out;
}
};
int main()
{
person p("code out the future",1);
p << cout; //注意
return 0;
}
二:关系运算符(这里以==以内,其他自己实现)
class person {
public:
person(int age) : age(age) {};
int age;
//类内
person operator==(person p1)
{
if (this->age > p1.age) return *this;
return p1;
}
};
//类外
person operator==(person p1, person p2)
{
if (p1.age > p2.age) return p1;
return p2;
}
int main()
{
person p1(18), p2(17), p3 = p2 == p1;
cout << p3.age;
return 0;
}
三:下标运算符[](操作对象的数组)
#include<iostream>
using namespace std;
#include<vector>
class A {
private:
vector<int>age = { 0,1,2,3,4 };
vector<int>height = { 121,2342,2352 };
public:
int& boys(int i)
{
return age[i];
}
//第一种声明,可查可改
//int& operator[](int i)
//{
// return age[i];
//}
//int a = 10;
//第二种,只能查
const int& operator[](int i) const
{
return age[i];
}
};
int main()
{
//常规
A a;
cout << a.boys(1) << endl;
a.boys(1) = 10;
cout << a.boys(1) << endl << endl << endl;
//第一种
A b;
cout << a[1] << endl;
a[1] = 100;
cout << a[1] << endl << endl << endl;
//第二种
A c;
cout << a[1] << endl;
// a[1] = 10000; //err
cout << a[1] << endl;
return 0;
}
四:赋值运算符=