CS106L 11
recap
-
Template是一个工厂,可以定制模板,对传入的参数进行加工,生成相应的功能产品 -
Const Correctness保证函数不能被改变size_t siez() const;
We Learned!
I/O libraryContainers libraryIterators libraryAlgorithms libraryConcepts library
We made it really far!
Operator
We Knnnnow!
Create classesCreate template
但是怎么
Create map、sets?其内部实现为红黑树,通过操作符
<来进行内部实现,那么通过
min实现如何?
About min
关于之前课程中实现的min操作,T必须存在排序关系,只有这样才能对其有意义,
而且T必须是可对比的,能够被逻辑化实现。
[!NOTE]
如果对整数实现
min可以,但是如何对结构体或者其他类型实现min操作?
Operator!
Operators can overloaded
+ - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= *= /= %= ^= &= |= <<= >>= [] () -> ->* new new[] delete delete[]
Operators can't overloaded
- 范围解析
:: - 三元
? - 成员访问
. - 指向成员的指针
.* - 对象大小、类型和转化
sizeof()、typeid()、cast()
对其他类型实现操作符对比运算
// .h file
class Student {
private:
std::string name;
std::string sunet;
int idNumber;
public:
Student(std::string name, std::string sunet, int idNubmer);
... // orther Interface
...
...
bool operator < (const StudentID& rhs) const;
}
// .cpp file
std::string Student::getName() {
return this->name;
}
...
bool Student::operator < (cosnt StudentID& other) const {
return idNumber < other.idNumber;
}
这种方式为成员重载Member overloading,在Class中定义了重载函数,
还有非成员重载Non-member overloading
- 包含左、右边
- 在
Class外声名定义
// Non-Member
bool operator < (const Student& lhs, const Student& rhs);
// Member
bool Student::operator < (const Student& rhs) const {...}
[!note]
在
Member中可以访问类成员变量和 this-> 指针在
Non-member中不可以,因为存在两个参数引用,不确定哪一个访问,所以不可以
friend keyword
- firend 键允许通过非成员函数或者类来访问在其他类中的私有信息
// .h file
class Student {
private:
std::string name;
std::string sunet;
int idNumber;
public:
Student(std::string name, std::string sunet, int idNubmer);
... // orther Interface
...
...
friend bool operator < (const StudentID&lhs, const StudentID& rhs);
}
// .cpp file
bool operator < (const Student& lhs, const Student& rhs) {
return lhs.idNumber < rhs.idNumber;
}
这样做有什么用?编译器可以 min(classa, classb)!
Student Liu;
Student SSS;
auto minStudent = min<Student>(Liu, SSsss);
Studnet min(const Student& a, const Student& b) {
returnn a < b ? a : b;
}
通常做什么
- 自定义类型 自定义操作比较
- PoLA 原则
- 对立法则简化函数实现
bool S::operator==(const S& other) const {
return (name == other.name) && (sunet == other.sunet) && (id == other.id)
}
// We can...
bool S::operator!=(const S& other) const {
return !(*this == other);
}
<<
std::ostream& operator << (std::ostream& out, const Student& sid) {
out << sid.name << " " << sid.sunet << " " sid.idNumber;
return out;
}
- 升级定义对象的功能
- 有意义,无法直接通过函数对其类型进行实现
- 只有需要时才重载运算符,如何类型不使用某一种操作,就不应该定义重载操作符
End...