/****************************************************
# File        : main.cpp
# Author      : lucasysfeng
# Revision    : 2014-10-13 17:04:43
# Description :
****************************************************/
#include <iostream>
using namespace std;

class A
{
public:
    A() { cout << "A constructor" << endl;  }
    ~A() { cout << "A destructor" << endl; }
    A(const A&) { cout << "A copy" << endl; }
    A& operator=(const A) { cout << "A assign" << endl; return *this; }
};

class B
{
public:
    B() { cout << "B constructor" << endl;  }
    // B(const A a) { _a = a; cout << "B constructor with arg" << endl;  }
    B(const A a) : _a(a) { cout << "B constructor with arg" << endl;  }
    ~B() { cout << "B destructor" << endl; }
    B(const B&) { cout << "B copy" << endl; }
    B& operator=(const B) { cout << "B assign" << endl; return *this;}
private:
    A _a;
};

int main(int argc, char** argv)
{
    A a;
    B b(a);

    return 0;
}

  

 

一般构造函数可以对数据成员赋值,那为什么需要初始化列表

举一个例子就可反证,有的数据成员并不能通过赋值进行初始化,因此初始化列表是必要的。

Effective C++

1.有些情况下必须用初始化——特别是const和引用数据成员只能用初始化,不能被赋值。

2.成员初始化列表的效率比赋值的效率高。

(在构造函数实现中赋值,需要调用构造函数和赋值构造函数;而用成员初始化列表只需

调用拷贝构造函数。)

下面程序错误:
#include <iostream>
using namespace std;

class Test {
private:
	const int a;
public:
	Test() {a = 0;}  //error,不能对const数据成员初始化。
};

int main()
{
	return 0;
}



下面程序正确:

#include <iostream>

using namespace std;

class Test {
private:
	const int a;
public:
	Test(): a(0) {}
};

int main()
{
	return 0;
}



相关文章:

  • 2021-11-25
  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-11
  • 2021-08-15
猜你喜欢
  • 2021-12-14
  • 2021-12-06
  • 2022-12-23
  • 2017-12-12
  • 2022-12-23
  • 2022-01-28
  • 2022-12-23
相关资源
相似解决方案