課程
/后端開發(fā)
/C++
/C++遠征之封裝篇(上)
還是沒有明白,拷貝構造函數(shù)和只顯示一個結果有什么聯(lián)系嗎?
2017-11-04
源自:C++遠征之封裝篇(上) 6-7
正在回答
有關系。那樣寫代碼的話后面兩行無法打印出來,S1調用了構造函數(shù),這樣S2,S3就必須調用拷貝構造函數(shù)才能夠將下兩行代碼打印出來
#include <iostream>
#include <string>
using namespace std;
/**
? * 定義類:Student
? * 數(shù)據(jù)成員:名字、年齡
? */
? class Student
{
public:
? ? // 定義數(shù)據(jù)成員名字 m_strName 和年齡 m_iAge
? ? string m_strName;
? ? int m_iAge;
};
int main()
? ? // 實例化一個Student對象stu
? ? Student stu;
? ? // 設置對象的數(shù)據(jù)成員
? ? stu.m_strName = "慕課網(wǎng)";
? ? stu.m_iAge = 2;
? ??
? ? // 通過cout打印stu對象的數(shù)據(jù)成員
? ? cout << stu.m_strName << " " << stu.m_iAge<< endl;
? ? return 0;
}
舉報
封裝--面向對象的基石,本教程力求幫助小伙伴們即學即會
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網(wǎng)安備11010802030151號
購課補貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動學習伙伴
掃描二維碼關注慕課網(wǎng)微信公眾號
2019-02-15
2017-11-04
#include <iostream>
#include <string>
using namespace std;
/**
? * 定義類:Student
? * 數(shù)據(jù)成員:名字、年齡
? */
? class Student
{
public:
? ? // 定義數(shù)據(jù)成員名字 m_strName 和年齡 m_iAge
? ? string m_strName;
? ? int m_iAge;
};
int main()
{
? ? // 實例化一個Student對象stu
? ? Student stu;
? ? // 設置對象的數(shù)據(jù)成員
? ? stu.m_strName = "慕課網(wǎng)";
? ? stu.m_iAge = 2;
? ??
? ? // 通過cout打印stu對象的數(shù)據(jù)成員
? ? cout << stu.m_strName << " " << stu.m_iAge<< endl;
? ? return 0;
}