在 C++ 中,初始化列表和在构造函数中赋值之间有什么区别,而不是每个方法看起来的方式? 我的意思是使用一个而不是另一个有什么好处,为什么在幻灯片(下面)的给定示例中只适用于初始化? (我没有找到,希望你能给它添加一些资源)
最佳答案
在构造函数中使用初始化列表是一步过程,即它在声明时初始化对象。它调用复制构造函数。
而使用赋值是两步过程,即定义对象然后赋值。定义对象调用默认构造函数,然后赋值调用赋值运算符。因此,昂贵的操作。
在C++中,类的常量或引用数据成员变量只能在初始化列表中初始化,不能在构造函数体中使用赋值。
常量和引用数据成员变量都具有必须在声明时初始化的特性。因此,只能在构造函数中使用初始化列表,因为初始化列表在声明时初始化类成员变量,而如果构造函数体赋值则在声明后初始化数据成员。
在某些情况下,构造函数中的数据成员初始化不起作用,必须使用 Initializer List。以下是这样的案例。
- 用于初始化非静态常量数据成员。
#include<iostream> using namespace std; class Test { const int t; public: Test(int t):t(t) {} //Initializer list must be used int getT() { return t; } }; int main() { Test t1(10); cout<<t1.getT(); return 0; }
- 用于引用成员的初始化。
#include<iostream> using namespace std; class Test { int &t; public: Test(int &t):t(t) {} //Initializer list must be used int getT() { return t; } }; int main() { int x = 20; Test t1(x); cout<<t1.getT()<<endl; x = 30; cout<<t1.getT()<<endl; return 0; }
- 用于初始化没有默认构造函数的成员对象。 (在你的情况下 Array digits 没有默认构造函数)
#include <iostream> using namespace std; class A { int i; public: A(int ); }; A::A(int arg) { i = arg; cout << "A's Constructor called: Value of i: " << i << endl; } // Class B contains object of A class B { A a; public: B(int ); }; B::B(int x):a(x) { //Initializer list must be used cout << "B's Constructor called"; } int main() { B obj(10); return 0; }
- 用于基类成员的初始化。
- 当构造函数的参数名称与数据成员相同时。
- 出于性能原因。
关于C++ 初始化列表与赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61721746/