網站首頁 編程語言 正文
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)//調用有參構造函數
總結
原文鏈接:https://blog.csdn.net/weixin_44190648/article/details/121948628
相關推薦
- 2022-10-24 iOS開發之Objective-c的Runtime理解指南_IOS
- 2022-10-02 C/C++寬窄字符轉換與輸出的多種實現方法_C 語言
- 2022-04-30 C#操作DataGridView設置單元格只讀_C#教程
- 2022-05-25 Starship定制shell提示符實現信息自由_python
- 2023-11-21 python使用print輸出不同顏色的字體、終端顯示不同顏色字體
- 2022-04-28 關于k8s中subpath的使用詳解_云其它
- 2022-02-15 eclipse配置Tomcat和Tomcat出現無效端口解決辦法_Tomcat
- 2022-04-07 Go語言中int、float、string類型之間相互的轉換_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支