1. C++17中引入size()函数用于计算数组的长度
int a[5];
int n = size(a);
2. 引用需要注意的地方
- 不能反悔局部变量的引用
- 函数的左值可以作为引用:
Stu& operator++();
- 引用的本质是指针常量
3. 运算符重载
+:operator+(Stu& s)
cout:Stu operator<<(ostream &cout, Stu& s)
前置++:Stu& operator++()
后置++:Stu operator++(int)
=赋值:Stu& operator=(Stu& s) //注意堆区内存的重复回收
==判断:bool operator==(Stu& s)
函数调用():void operator()()
4. 菱形继承
为了防止D的对象出现二义性,需要在B和C继承A时使用virtural
关键字
#include <iostream>
using namespace std;
class A
{
public:
A(){
n = 4;
}
int n;
};
class B: virtual public A {};
class C: virtual public A {};
int main(){
D d;
/* 无virtual时
cout << d.B::n << endl;
cout << d.C::n << endl;
*/
// 有了virtual可以直接得出d的属性,继承自A
cout << d.n << endl;
}
5. 多态
定义:多态是指一条语句根据对象的不同有不同的执行结果。
发生条件:
a. 有继承关系
b. 子类重写父类的虚函数
c. 父类的指针或引用执行子类的方法
#include <iostream>
using namespace std;
class People {
public:
virtual void speak(){
cout << "I'm people!" << endl;
}
} ;
class Student: public People {
public:
void speak(){
cout << "I'm student" << endl;
}
};
void test1() {
Student* ps = new Student();
People* li = ps;
li->speak();
}
int main(){
test1();
}
输出
I'm student
6. 异常退出
可使用exit(1)实现程序的异常退出,返回主进程1,表示程序是异常退出。(如果返回0表示程序执行正常)
int main(){
int a = 10;
if (a != 1) { // 想对a做判断,如果不为1则异常退出
cout << "a is not 1" << endl;
exit(1);
}
}
以上程序的输出为
a is not 1