C++Tips

表达式赋值

在C++中有些表达式是可以被赋值的

int a = 10;
int b = 20;
(a = b) =3;
(a < b ?a : b) = 4

C++中的仿函数

把对象当做一个函数使用,实现关键是重载函数运算符(),作为对象可以保存状态,通常可以用于工厂类内部

class Obj
{
public:
    Obj() {};
    ~Obj() {};
};


class Test{
    public:
        explicit Test(char type) : m_type(type){}
        Obj* operator() (int a,int b){ //实现工厂模式中,利用不同的type返回不同的对象
            Obj *obj = nullptr;
            switch(m_type)
            {
                case 'i':
                    obj = new Obj();
                    break;
                case 'o':
                    obj = new Obj();
                    break;

            }
            return obj;

        }

    private:
        const char m_type;

};

struct 和class

在C++中struct和class都可以定义一个类,struct 的默认成员权限是public,class的默认权限是private,这是2者唯一的区别,其他都一样。既然差别很小,为什么要使用struct呢,这个原因大概是为了让C语言的开发者更好的过渡到C++。

posted @ 2021-08-05 15:39  弄啥来  阅读(43)  评论(0)    收藏  举报