CS106L 11

130 阅读2分钟

CS106L 11

recap

  • Template是一个工厂,可以定制模板,对传入的参数进行加工,生成相应的功能产品

  • Const Correctness保证函数不能被改变

    size_t siez() const;
    

We Learned!

  • I/O library
  • Containers library
  • Iterators library
  • Algorithms library
  • Concepts library

We made it really far!


Operator

We Knnnnow!

  • Create classes
  • Create 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...