Loading

侯捷c++课程笔记: 一些补充

OOP

static

static member

在类的主体定义数据成员时在前面添加static,则一个类只有一份数据,作为整个类公有的数据
没有添加的则每个对象一份数据

static function

在函数定义前加上static即为静态成员函数
与普通成员函数不同,静态成员函数没有this指针这个参数,因此只能访问静态变量
调用static函数可以通过object调用,也可以用class name调用

static可以用于singleton设计模式,将构造函数设计为private,只允许存在一个实例对象

class A
{
private:
    
    A(){
        cout<<"ctor"<<endl;
    }
    static A a;
public:
    static A& getInstance();
};
A& A::	getInstance()
{
    static A a;
    return a;
}

助记:
全局静态变量与全局变量类似,不同之处在于只限于本文件内可见
在函数体定义的为局部静态变量,在离开函数体后,作用域依旧存在,直到程序结束

cout

c++的cout能够输出多种类型,原因是其内部重载了各种operator <<

template

class template

通过template<typename T>声明一个模板类,在使用时需要指定typename,如vector<int> arr
类模板可能会造成代码膨胀,但这是必要的,且是合理的

function template

同样在函数声明前template<class T> class和typename是一样的

template<class T>
inline
const T& min(const T& a, const T& b)
{
    return b < a ? b : a;
}

编译器会对function template进行argument deduction,故使用时不必指定typename

namespace

为了防止重名,可以将变量名封装在一个命名空间中
有三种使用方法
using directive:using namespace std; cout<<"hello";
using declaration:using std::cout; cout<<"hello";
直接使用:std::cout<<"hello";

int+float

假设int x=3; float y=1.6;
x+=y 先执行x+y,对x进行类型转换,结果为float 4.6
将4.6赋值给x,结果为4

posted @ 2021-09-13 23:32  traver  阅读(46)  评论(0编辑  收藏  举报