在 C++ 中,初始化列表和在构造函数中赋值而不是每个方法的外观有什么区别?
我的意思是使用其中一种而不是另一种的优势是什么,为什么在幻灯片(如下)的给定示例中仅适用于初始化? (我希望你能添加一些资源,因为我没有找到)
点击此处查看幻灯片:已上传至 imgur https://i.stack.imgur.com/1pBoX.jpg
在构造函数中使用初始化列表是一步过程,即它在声明对象时初始化对象。它调用复制构造函数。
而使用赋值是一个两步过程,即定义对象然后对其进行赋值。定义对象调用默认构造函数,然后赋值调用赋值运算符。因此,操作成本高昂。
在C++中,类的常量或引用数据成员变量只能在初始化列表中初始化,而不能在构造函数体内使用赋值。
常量和引用数据成员变量都具有必须在声明时初始化的属性。因此,只有在构造函数中使用初始化列表的方法,因为初始化列表在声明时初始化类成员变量,而构造函数体的赋值在声明后初始化数据成员。
在某些情况下,构造函数内的数据成员初始化不起作用,必须使用初始化器列表。以下是此类案例。
- 用于非静态 const 数据成员的初始化。
#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;
}
- 用于初始化没有默认构造函数的成员对象。 (在你的情况下数组数字没有默认构造函数)
#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;
}
- 用于基类成员的初始化。
- 当构造函数的参数名称与数据成员相同时。
- 出于性能原因。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)