首页 > 作文

C++构造函数的初始化列表详解

更新时间:2023-04-04 03:40:23 阅读: 评论:0

目录
1.问题2.解决方法(初始化列表)3.顺序问题总结

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)//调用有参构造函数

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注www.887551.com的更多内容!

本文发布于:2023-04-04 03:40:22,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/879441d3763d5d9fda48fa6f7b616597.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:C++构造函数的初始化列表详解.doc

本文 PDF 下载地址:C++构造函数的初始化列表详解.pdf

标签:函数   顺序   初始化   列表
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图