美文网首页
右值引用、五大函数、静态成员、友元函数

右值引用、五大函数、静态成员、友元函数

作者: wjundong | 来源:发表于2020-01-07 11:49 被阅读0次

    右值引用

    参考这篇知乎文章

    五大函数

    #include <iostream>
    
    #define p(s) std::cout << s << std::endl
    
    class shape {
    public:
        shape()                             {                 }
        ~shape()                            {  p("析构函数");  }
        shape(const shape &rhs)             {  p("拷贝构造");  }
        shape(shape &&rhs)                  {  p("移动构造");  }
        shape &operator=(const shape &rhs)  {  p("拷贝赋值");  }
        shape &operator=(shape &&rhs)       {  p("移动赋值");  }
    };
    
    
    int main()
    {
        shape a;
    
        // 拷贝构造,等价于 shape b(a); 或 shape b = shape(a);
        shape b = a; 
        shape c = std::move(a); // 移动构造
        b = c;                  // 拷贝赋值
        b = std::move(c);       // 移动赋值 
        std::cout << std::endl;
        
        // 先拷贝构造然后移动赋值最后将旧的 b 析构
        b = shape(c);           
    
        std::cout << std::endl;
    }
    

    输出结果

    拷贝构造
    移动构造
    拷贝赋值
    移动赋值
    
    拷贝构造
    移动赋值
    析构函数
    
    析构函数
    析构函数
    析构函数
    

    静态成员

    • 静态成员是整个类共有的,所有类的对象都可以访问
    • 静态成员需在类外定义和初始化,无法在类内定义和初始化
    • 静态成员类加载时就定义,不需要创建对象
    • 静态成员函数只能访问静态成员变量,非静态成员函数可以访问静态成员变量
    #include <iostream>
    
    class shape 
    {
    private:
        // 声明私有静态成员
        static int sValue;
    
    public:
        static int pubsValue;
        // 对象的成员函数,可访问静态成员
        inline void setValue(int val) { sValue = val; }
        inline int getValue() { return sValue; }
    };
    
    // 在外部定义静态成员并初始化
    int shape::sValue = 0;
    int shape::pubsValue = 0;
    
    
    int main()
    {
        shape shap;
        shap.setValue(12);
    
        // 公开的静态成员可以通过对象或类名直接访问
        shap.pubsValue = 20;
        shape::pubsValue = 223;
    
        std::cout << shape::pubsValue << std::endl;
    }
    

    友元函数

    #include <iostream>
    
    // shape 类前声明类 rect
    class rect;
    
    class shape {
    public:
        // 被 rect 标记为友元的函数
        void printShape(rect rect);
    };
    
    class rect {
    private:
        int mValue;
    public:
        rect(int val)  { mValue = val; }
        // 友元函数,允许该函数访问自己私有变量
        friend void shape::printShape(rect rect);
    };
    
    // 函数定义需在 rect 类定义后
    void shape::printShape(rect rect)
    {
        std::cout << rect.mValue << std::endl; 
    }
    
    
    int main()
    {
        shape shap;
        rect rect(24);
    
        shap.printShape(rect);
    }
    

    相关文章

      网友评论

          本文标题:右值引用、五大函数、静态成员、友元函数

          本文链接:https://www.haomeiwen.com/subject/hgdractx.html