对比c++类的两种成员初始化方式

#include <iostream>

using namespace std;

struct SData
{
  SData() { std::cout << "default construct" << std::endl; }
  SData(int value) : a(value) { std::cout << "construct" << std::endl; }
  SData(const SData& oData)
  {
    a = oData.a;
    std::cout << "copy assignment" << std::endl;
  }
  void operator=(const SData& oData)
  {
    a = oData.a;
    std::cout << "assignment" << std::endl;
  }

  int a = 0;
};

class A
{
  public:
    A(const SData& oData) : m_oData(oData) {}

  private:
    SData m_oData;
};

class B
{
  public:
    B(const SData& oData) { m_oData = oData; }

  private:
    SData m_oData;
};

int main()
{
  SData oData(10);
  std::cout << "test begin A ---------------------:" << std::endl;
  A oClassA(oData);
  std::cout << "test begin B ---------------------:" << std::endl;
  B oClassB(oData);

  return 0;
}

 

output:

construct
test begin A ---------------------:
copy assignment
test begin B ---------------------:
default construct
assignment

posted @ 2020-06-24 20:29  upupon  阅读(191)  评论(0编辑  收藏  举报