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

2020-01-07  本文已影响0人  wjundong

右值引用

参考这篇知乎文章

五大函数

#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);
}
上一篇下一篇

猜你喜欢

热点阅读