1. 防止头文件的重复包含
#ifndef __TEST_H__
#define __TEST_H__
class Test
{
public:
Test();
};
#endif // __TEST_H__
否则会显示, 常见的error: redefinition of ‘class Test’
error: previous definition of ‘class Test’
因为头文件包含后,预处理器会将所有的被包含文件内容全部复制到对应的文件中,如果不加如#ifndef...,则可能会将这些内容拷贝
多次到包含文件中,造成重复定义.
2. String中的<<操作符
//main.cpp
#include <iostream>
#include "mystring.h"
int main()
{
String s1("Good");
String s2("morning");
String s3("my life");
std::cout << s1 << " " << s2 << " " << s3 << std::endl; //可以连续<<
return 0;
}
//给自己定义的String类定义<<操作符号,注意函数形式
#include <iostream>
std::ostream& operator << (std::ostream& os, const String& str)
{
os << str.get_c_str(); //函数:char* get_c_str() const {return m_data;}
return os;
}
//结果: Good morning my life
3. virtual虚函数
1).静态编联, 在编译的时候就确定了调用哪一个函数, 看的是指针本身的类型来调用对应的函数
class Base
{
public:
//没有virtual修饰
void display()
{
std::cout << "Base::display()" << std::endl;
}
};
class Derived_A : public Base
{
public:
void display()
{
std::cout << "Derived_A::display()" << std::endl;
}
};
int main()
{
Base *bp = new Base();
bp->display();
//Base::display()
Base *dp = new Derived_A();
dp->display(); //Base中display没有virtual修饰,所以即使用基类指针指向派生类对象是,调用
//的也是指针类型(Base)类的display函数
//Base::display()
return 0;
}
2)动态编联, 多态的体现,通过基类的virtual函数的继承来实现, 指针调用时看的是指针指向的对象的类所对应的函数
class Base
{
public:
virtual void display() //virtual函数
{
std::cout << "Base::display()" << std::endl;
}
};
class Derived_A : public Base
{
public:
void display()
{
std::cout << "Derived_A::display()" << std::endl;
}
};
int main()
{
Base *bp = new Base();
bp->display();
//Base::display()
Base *dp = new Derived_A();
dp->display();//基类中为virtual,所以调用的函数是指针指向的对象的类型中的
//函数,而不是看指针的类型. 实现了多态.
//Derived_A::display()
return 0;
}
4. virtual继承: 为了解决多重继承中有共同的基类(菱形继承)时的问题. 需要使用virtual继承的方式.
摘自夏曹俊老师的视频
5.使用using关键字取别名
#include <iostream>
namespace space {
template<class T> using ptr = T*;
}
int add(int a, int b)
{
return a+b;
}
//函数指针的方式
typedef int(*ADD)(int a, int b);
//使用using关键字取别名的方式
using FUNC = int(*)(int a, int b);
using co = std::ios_base::fmtflags;
int main()
{
ADD pAdd = add;
std::cout << pAdd(1,2) << std::endl;//3
FUNC func = add;
std::cout << func(3,4) << std::endl;//7
space::ptr<int> pint(new int(15));
std::cout << *pint << ", " << pint << std::endl;//15, 0x1564030
return 0;
}
6. 调试与静态断言