什么是友元
C++ 面向对象的特点是数据封装和数据隐藏。
然而,某些类外部函数可能要使用类内部成员变量,这就需要将成员变量设置为 public,但是会导致数据隐藏功能失效。
也可以考虑在类的内部开放成员变量 get 方法,但是这样操作比较麻烦。
所以,给类外部的指定函数设置特权,可以访问类内部的私有成员变量,这样的特权函数就叫做友元。
#include <iostream>
#include <cstdio>
using namespace std;
class Complex{
friend Complex add(const Complex&, const Complex&);
private:
int m_i;
int m_j;
public:
Complex(int i, int j): m_i(i), m_j(j){}
void output(){
printf("(%d,%d)\n", m_i, m_j);
}
};
Complex add(const Complex& c1, const Complex& c2){
return Complex(c1.m_i + c2.m_i, c1.m_j + c2.m_j);
}
int main() {
Complex c1(10, 20);
Complex c2(30, 40);
Complex c3 = add(c1, c2);
c3.output();
return 0;
}
#include <iostream>
#include <cstdio>
using namespace std;
class Complex{
friend Complex operator+(const Complex&, const Complex&);
private:
int m_i;
int m_j;
public:
Complex(int i, int j): m_i(i), m_j(j){}
void output(){
printf("(%d,%d)\n", m_i, m_j);
}
};
Complex operator+(const Complex& c1, const Complex& c2){
return Complex(c1.m_i + c2.m_i, c1.m_j + c2.m_j);
}
int main() {
Complex c1(10, 20);
Complex c2(30, 40);
Complex c3 = c1 + c2;
c3.output();
return 0;
}
#include <iostream>
#include <cstdio>
using namespace std;
class Complex{
private:
int m_i;
int m_j;
public:
Complex(int i, int j): m_i(i), m_j(j){}
void output(){
printf("(%d,%d)\n", m_i, m_j);
}
Complex operator+(const Complex& x) const{
return Complex(m_i + x.m_i, m_j + x.m_j);
}
};
int main() {
Complex c1(11, 22);
Complex c2(30, 40);
Complex c3 = c1 + c2;
c3.output();
return 0;
}
运算符重载
运算符重载就是给运算符赋予一些新的功能。比如,<<
既是位移运算符,又可以配合 cout 向控制台输出数据。
这是由于 C++ 对 <<
运算符进行重载操作。
#include <iostream>
#include <cstdio>
using namespace std;
class Complex{
friend ostream& operator<<(ostream&, const Complex&);
friend istream& operator>>(istream&, const Complex&);
private:
int m_i;
int m_j;
public:
Complex(){}
Complex(int i, int j): m_i(i), m_j(j){}
void output(){
printf("(%d,%d)\n", m_i, m_j);
}
// 单目运算符重载
Complex operator-() const{
return Complex(-m_i, -m_j);
}
// 前置++ : ++对象
Complex& operator++(){
++m_i;
++m_j;
return *this;
}
// 后置++:对象++
Complex operator++(int){
Complex pre(m_i, m_j);
m_i++;
m_j++;
return pre;
}
};
ostream& operator<<(ostream& cout, const Complex& x){
printf("(%d,%d)", x.m_i, x.m_j);
return cout;
}
istream& operator>>(istream& cin, const Complex& x){
scanf("%d%d", &x.m_i, &x.m_j);
return cin;
}
int main() {
Complex c1(11, 22);
Complex c2(30, 40);
Complex c3 = c2++;
// cout << c1 << " " << c2 << endl;
Complex c4;
cin >> c4;
cout << c4 << endl;
// c3.output();
// c2.output();
return 0;
}