六、C++学习_友元函数(带C语言基础)
解决运算符重载问题
Integer int5, int4, int3; //自己封装的类
int5 = int3 + int4; //重载+运算符 实现 int3.value + int4.value
int5 = int4 + 1024; //编译通过
int5 = 1024 + int4; //编译报错
- 友元函数
//使用友元方式重载+运算符,实现int类型与Integer类型的相加;
friend const Integer operator+(int intvalue, const Integer &other);//声明
//函数实现 注:不加作用域
const Integer operator+(int intvalue, const Integer &other){
return Integer(intvalue + other.m_value);
}
//友元函数重载流运算符 实现打印类中私有成员值
friend ostream &operator<<(ostream &out, const Integer &num){
out << num.m_value << endl;
}
//友元函数重载流运算符 实现打印类中私有成员值
friend istream &operator<<(istream &in, const Integer &num){
out << "请输入一个整数:" << endl;
in >> num.m_vslue;
return in;
}