1.问题
class A {
private:
int m_a;
public:
A(int a) {
cout << "A(int a)......." << endl;
m_a = a;
}
void print() {
cout <<"m_a=" << m_a << endl;
}
};
class B {
private:
int m_b;
A m_a1;
A m_a2;
public:
B(A& a1,A& a2, int b)
{
m_b = b;
m_a1(a1);//此处调用A的拷贝函数会报错
m_a2(a2);//此处调用A的拷贝函数会报错
}
};
错误:
2.解决方法(初始化列表)
将class B构造函数改写为:
public:
B(A& a1,A& a2, int b) :m_a1(a1),m_a2(a2)//构造函数的初始化列表
{
m_b = b;
}
};
完整代码如下:
#include <iostream>
using namespace std;
class A {
private:
int m_a;
public:
A(int a) {
cout << "A(int a)......." << endl;
m_a = a;
}
void print() {
cout <<"m_a=" << m_a << endl;
}
A(const A& another) {
m_a = another.m_a;
}
~A() {
cout << "~A()......" << endl;
}
};
class B {
private:
int m_b;
A m_a1;
A m_a2;
public:
B(A& a1,A& a2, int b) :m_a1(a1),m_a2(a2)//构造函数的初始化列表,调用拷贝构造
{
cout << "B(A& a1,A& a2, int b)......." << endl;
m_b = b;
}
~B() {
cout << "~B()......." << endl;
cout << "m_b=" << m_b << endl;
cout << "A m_a1" << endl;
m_a1.print();
cout << "A m_a2" << endl;
m_a2.print();
}
};
int main(int argc, char** argv) {
A a1(1), a2(2);
B b1(a1, a1, 3);
}
运行结果:
3.顺序问题
构造对象成员的顺序跟初始化列表的顺序无关,而是跟成员对象定义的顺序有关。(面试会问)
例子:
class A {
private:
int m_a;
public:
A(int a) {
cout << "A(int a)......." <<a<< endl;
m_a = a;
}
void print() {
cout <<"m_a=" << m_a << endl;
}
A(const A& another) {
m_a = another.m_a;
}
~A() {
cout << "~A()......"<< endl;
}
};
class B {
private:
int m_b;
A m_a2;
A m_a1;
public:
B(int a1, int a2, int b) :m_a1(a1), m_a2(a2)//调用有参构造函数
{
cout << "B(int a1, int a2, int b)......." << endl;
m_b = b;
}
~B() {
cout << "~B()......." << endl;
}
};
int main(int argc, char** argv) {
B b2(1, 2, 3);
}
结果:
跟下面顺序有关:
private:
A m_a2;
A m_a1;
跟下面顺序无关:
B(int a1, int a2, int b) :m_a1(a1), m_a2(a2)//调用有参构造函数
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程学习网的更多内容!
沃梦达教程
本文标题为:C++构造函数的初始化列表详解
基础教程推荐
猜你喜欢
- C利用语言实现数据结构之队列 2022-11-22
- 一文带你了解C++中的字符替换方法 2023-07-20
- C++中的atoi 函数简介 2023-01-05
- C语言基础全局变量与局部变量教程详解 2022-12-31
- C++详细实现完整图书管理功能 2023-04-04
- C/C++编程中const的使用详解 2023-03-26
- 如何C++使用模板特化功能 2023-03-05
- 详解c# Emit技术 2023-03-25
- C语言 structural body结构体详解用法 2022-12-06
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26