目录
1?友元类
2?友元函数
3?运算符重载(类)
一、加减法
(1)类内
(2)全局
二、左移运算符
4?自定义整型
5?前置后置++运算符
一些疑问
6?运算符“=”
?7 一份收获(当类的属性是指针时,重载运算符出现错误的解决办法)
8?仿函数
友元类
让朋友能读到我的私有东西

#include<iostream>
using namespace std;
class people;
class son { //儿子是人的朋友,儿子是人的友元类。
public:
son(); //编译器可能没读到一些声明定义,可在类外写成员函数,包括构造。
void visit();
private:
people* people_; //人的指针,初始化时会创建一个堆。
int no;
};
class people {
friend class son;//声明儿子是人的朋友。友元类。能让儿子读到我私有的东西。(关键)
public:
people() {
pub = 233;
pri = 666;
}
int pub;
private:
int pri;
};
son::son() {
no = 0;
people_ = new people;
};
void son::visit() {
cout << "你的儿子在看你的公开读物" << people_->pub << endl;
cout << "你的儿子在看你的隐私读物" << people_->pri << endl;
}
void test() {
son a;
a.visit();
}
int main() {
test();
}
友元函数
一个类访问不到另一个类的私有变量,所以要在被访问的地方添加访问函数的友元声明
#include<iostream>
using namespace std;
class people;
class son {
public:
son();
void visit1(); //<---------------1.访问函数声明
private:
people* people_;
int no;
};
class people {
friend void son::visit1(); //<---------------2.访问函数友元声明,加"类::"(关键)
public:
people() {
pub = 233;
pri = 666;
}
void show() {
cout << "people 展示自己的公共物品:" << pub << endl;
}
int pub;
private:
int pri;
};
son::son() {
no = 0;
people_ = new people;
};
void son::visit1() {
cout << "你的儿子在看你的隐私读物" << people_->pri << endl; //<---3.写访问函数
}
void test() {
son a;
a.visit1(); //<---------------3.调用访问函数
}
int main() {
test();
}
运算符重载(类)
一、加减法
(1)类内
people是返回

(2)全局

上面是下面的简化

二、左移运算符
不能利用成员函数重载左移运算符,因为(“.” 调用时)无法实现cout在左侧

?链式编程思想

?cout和c是计算对象,<<是计算符号。return返回计算的值。
cout是ostream的引用名称,返回的就是的cout是这个。?
?自定义整型

前置后置++运算符
a++,先输出再++
++a,先++再输出

?void函数提示错误:C2679?? ?二元“<<”: 没有找到接受“void”类型的右操作数的运算符(或没有可接受的转换)?
一些疑问
(1)不能实现。看别人说是:“后置++使用移位运算符重载 不能定义引用 ,因为返回的临时对象temp已被编译器释放”。

(2)可实现。

运算符“=”
链式编程


?一份收获(当类的属性是指针时,重载运算符出现错误的解决办法)
类↓
class people{
int* age;
public:
people(int age_) {
age = new int(age_);
}
void show_age();
people& operator++();
people& operator=(people& p);
};
void people::show_age() {
cout << *(this->age) << endl;
}
people& people::operator++() {
*age++;
return *this;
//this->age = new int(++*(this->age));
}
结果:

解决:
people& people::operator++() {
this->age = new int(++*(this->age));
return *this;
//*age++;
}
我的理解是:将对象A的属性age指针加“*”获取数值后,加1,放在一个新的堆中,再让对象A的属性age指针指向这个堆。
仿函数
使用起来像是调用函数,因此称仿函数。
??重载 “()”

X(a,b)
函数调用,X是函数名
仿函数,X是实例化对象名字
|