課程
/后端開發(fā)
/C++
/C++遠(yuǎn)征之封裝篇(上)
?// 實(shí)例化一個(gè)Student對象stu
? ? Student stu = new student ;這樣為什么不可以
?cout?<<?stu.m_iAge<<?"student's?m_strName?is?"?<<stu.m_strName?<<?endl
通過cout打印stu對象的數(shù)據(jù)成員可以這樣嗎,為什么
2015-05-16
源自:C++遠(yuǎn)征之封裝篇(上) 3-2
正在回答
實(shí)例化時(shí)調(diào)用其構(gòu)造函數(shù),比如class?A,實(shí)例化時(shí)就先定義??A?a=new?A();
你那樣直接對類本身操作,不能
liuzhiwei 提問者
#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()
? ? // 實(shí)例化一個(gè)Student對象stu
? ? Student stu;
? ? // 設(shè)置對象的數(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;
}
舉報(bào)
封裝--面向?qū)ο蟮幕窘坛塘η髱椭』锇閭兗磳W(xué)即會(huì)
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網(wǎng)安備11010802030151號
購課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動(dòng)學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號
2015-05-21
實(shí)例化時(shí)調(diào)用其構(gòu)造函數(shù),比如class?A,實(shí)例化時(shí)就先定義
??A?a=new?A();
你那樣直接對類本身操作,不能
2015-05-16
#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()
{
? ? // 實(shí)例化一個(gè)Student對象stu
? ? Student stu;
? ? // 設(shè)置對象的數(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;
}