課程
/后端開(kāi)發(fā)
/C++
/C++遠(yuǎn)征之封裝篇(上)
答案有問(wèn)題,編譯不通過(guò)
2016-08-26
源自:C++遠(yuǎn)征之封裝篇(上) 4-3
正在回答
樓主,你沒(méi)有給stu 分配空間啊。看二樓代碼
#include?<iostream> #include?<string> using?namespace?std; /** ??*?定義類:Student ??*?數(shù)據(jù)成員:m_strName ??*?數(shù)據(jù)成員的封裝函數(shù):setName()、getName() ??*/ class?Student { public: ????//?定義數(shù)據(jù)成員封裝函數(shù)setName() ????void?setName(string?_name) ????{ ????????m_strName?=?_name; ????} ???? ???? ????//?定義數(shù)據(jù)成員封裝函數(shù)getName() ????string?getName(){ ????????return?m_strName; ????} ???? ???? //定義Student類私有數(shù)據(jù)成員m_strName private: ????string?m_strName; }; int?main() { ????//?使用new關(guān)鍵字,實(shí)例化對(duì)象 Student?*str?=?new?Student(); ????//?設(shè)置對(duì)象的數(shù)據(jù)成員 str->setName("慕課網(wǎng)"); ????//?使用cout打印對(duì)象str的數(shù)據(jù)成員 ????cout?<<?str->getName()?<<?endl; ????//?將對(duì)象str的內(nèi)存釋放,并將其置空 delete?str; str?=?NULL; return?0; }
#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對(duì)象stu
? ? Student stu;
? ? // 設(shè)置對(duì)象的數(shù)據(jù)成員
? ? stu.m_strName = "慕課網(wǎng)";
? ? stu.m_iAge = 2;
? ??
? ? // 通過(guò)cout打印stu對(duì)象的數(shù)據(jù)成員
? ? cout << stu.m_strName << " " << stu.m_iAge<< endl;
? ? return 0;
}
舉報(bào)
封裝--面向?qū)ο蟮幕?,本教程力求幫助小伙伴們即學(xué)即會(huì)
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號(hào)-11 京公網(wǎng)安備11010802030151號(hào)
購(gòu)課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動(dòng)學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號(hào)
2016-09-26
樓主,你沒(méi)有給stu 分配空間啊。看二樓代碼
2016-08-29
2016-08-26
#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對(duì)象stu
? ? Student stu;
? ? // 設(shè)置對(duì)象的數(shù)據(jù)成員
? ? stu.m_strName = "慕課網(wǎng)";
? ? stu.m_iAge = 2;
? ??
? ? // 通過(guò)cout打印stu對(duì)象的數(shù)據(jù)成員
? ? cout << stu.m_strName << " " << stu.m_iAge<< endl;
? ? return 0;
}