内容

重载示例

在这里就列举几个比较特殊的①输出

void operator <<(ostream& a, const CStu& st)
{
a << st.nAge <<endl;
}
int main()
{
CStu st;
cout << st;//这里不能加换行
system("pause");
return 0;
}

注意:cout是ostream的对象,cin是istream的对象。
这里也可以加上返回值,可以连续输出

ostream& operator <<(ostream& a, CStu& st)
{
a << st.nAge <<endl;
return a;
}
int main()
{
CStu st;
cout << st<<3;//这里不能加换行
system("pause");
return 0;
}

②输入

void operator >>(istream& a,  CStu& st)
{
a >> st.nAge;
}
int main()
{
CStu st;
cin >> st;//这里不能加换行
cout << st.nAge<< endl;
system("pause");
return 0;
}

注意:输入重载要进行输入是否正确的检验

istream& operator >>(istream& a,  CStu& st)
{
a >> st.nAge>>st.nHeight;
if (a.fail())//fail()是istream的一个成员函数,如果输入错误,返回1
{
cout << "输入失败" << endl;
st.nAge = 0;
st.nHeight = 0;
}
return a;
}
int main()
{
CStu st;
cin >> st;
cout << st.nAge<< endl;
cout << st.nHeight << endl;
system("pause");
return 0;
}

输入输出必须在类外,如果数据成员是private的,那就把函数设置为友元函数。③赋值运算符

class CStu
{
public:
int nAge;
CStu()
{
nAge = 0;
}
int operator=(int a)
{
nAge = a;
return a;
}
};

int main()
{
CStu st;
cout << (st = 113);
system("pause");
return 0;
}

注意:赋值运算符即=必须是类内重载。复合赋值运算符如+=建议类内。类内重载别忘了把左参数去掉,原因前面写过④下标运算符

class CStu
{
public:
int a;
int b;
int c;
int nError;
CStu()
{
a = 12;
b = 23;
c = 34;
nError = -1;
}
int& operator[](int a)
{
switch (a)
{
case 0:
return a;
case 1:
return b;
case 2:
return c;
}
return nError;
}
};

int main()
{
CStu st;
cout << st[1] << endl;
st[1] = 14;//要想能够改变里面的值,就传引用。也就是返回值是引用
cout << st[1] << endl;
system("pause");
return 0;
}

注意:[]必须是类内。
上面的代码,返回int&有漏洞,如果在数据成员里面再加上一个double类型,就不能返回double了。这时我们用通用类型的指针。(实际使用中不建议这样写,在这里只是为了更加深入理解指针才写出来的)

void* operator[](int a)
{
switch (a)
{
case 3:
return &d;
}
return &nError;
}
};

int main()
{
CStu st;
cout << *(double*)st[3] << endl;//注意这里,要把通用类型的指针转换回double类型的指针
system("pause");
return 0;
}

一般数据类型的指针转换为void✳一般不会出问题,但是由void✳转换成一般数据类型的指针就有可能出问题了,这时候我们一般进行一个强转。⑤自加自减运算符

int operator++(CStu& se, int n)
{
return 0;
}
int operator++(CStu& se)
{
return 0;
}
int main()
{
CStu st;
st++;
++st;
system("pause");
return 0;
}

注意:类内类外都可以,并且参数有int n就是后置自加,无int n就是前置自加。可以把n看成一个标志。
后置自加的逻辑是这样的

int operator++(CStu& se, int n)
{
int a = se.nAge;
se.nAge += 1;
return a;
}

⑥类型转换重载注意

1.没有显示返回类型,但是要写返回值
2.没有参数
3.必须是类内
4.不应该改变对象的内容,所以是const函数

class CStu
{
public:
int nAge;
double d;
CStu()
{
nAge = 11;
d = 11.11;
}
operator int() const//强制转换成整型
{
return nAge;
}
operator double() const//强制转换成浮点型
{
return d;
}
};

int main()
{
CStu st;
cout << (int)st << endl;
cout << (double)st << endl;
system("pause");
return 0;
}