Class 和 Structs
Structs
结构和类的区别:
结构体的参数默认访问为public; 类的参数默认访问是private
结构体继承默认是public继承;类的继承默认是private
都可以有成员变量和成员函数
| 1 | struct Student{ | 
struct里也可以重载运算符1
2
3
4
5
6
7
8struct Workshops{
    int start_time;
    int duration;
    int end_time;
    bool operator<(const Workshops &rhs){
        return (this->end_time < rhs.end_time);
    }
};
class
c++ 是面向对象设计的程序语言
- public: Public members (variables, methods) can be accessed from anywhere the code is visible.
- private: Private members can be accessed only by other member functions, and it can not be accessed outside of class.
| 1 | class SampleClass { | 
类里的参数初始化
使用类名+(){
}
多态
多态:同一个行为具有多个不同表现形式或形态的能力,表现为: 重载和覆盖
- 重载: 重载指再相同作用域中存在多个同名函数,这些函数的参数表不同,编译器可以根据不同的参数表选择不同的同名函数。 
- 覆盖:函数名,返回值,参数表都相同,子类重写从基类继承过来的函数 
举例:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50class Box{
public:
    int l,b,h;
    Box(){ //重载
        l=0;
        b=0;
        h=0;
    }
    Box(int aa, int ab, int ac){//重载
        l = aa;
        b = ab;
        h = ac;
    }
    Box(const Box& temp){//重载
        l=temp.l;
        b=temp.b;
        h = temp.h;
    }
    int getLength(){
        return l;
    }    
    int getBreadth(){
        return b;
    }
    int getHeigth(){
        return h;
    }
    long long CalculateVolume(){
        return (long long)l*b*h;
    }
    bool operator<(Box& temp){// 对操作符的重载
        if(this->l<temp.l){
            return true;
        }
        else if (this->b<temp.b&&this->l==temp.l) {
            return true;
        }else if (this->b<temp.b&&this->l==temp.l&&this->h<temp.h) {
            return true;
        }else {
            return false;
        }
        
        
    }
    friend ostream& operator<<(ostream& out, Box& B){// 对操作符的重载,"<<"需要用到ostream& 
        out<<B.l<<" "<<B.b<<" "<<B.h;
        return out;
    }
    
};
