課程
/后端開發(fā)
/C++
/C++遠(yuǎn)征之封裝篇(上)
為什么 ? // 使用new關(guān)鍵字,實(shí)例化對象 Student *str = new Student(); ? 需要括號???
2018-01-27
源自:C++遠(yuǎn)征之封裝篇(上) 4-3
正在回答
可以沒有括號,加括號只是起到初始化內(nèi)存的作用
加括號應(yīng)該會多調(diào)用一個(gè)構(gòu)造函數(shù),但這里又沒用到構(gòu)造函數(shù),所以加不加應(yīng)該無所謂
#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 = new student;
? ? // 設(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ū)ο蟮幕?,本教程力求幫助小伙伴們即學(xué)即會
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網(wǎng)安備11010802030151號
購課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號
2018-01-27
可以沒有括號,加括號只是起到初始化內(nèi)存的作用
2019-04-27
加括號應(yīng)該會多調(diào)用一個(gè)構(gòu)造函數(shù),但這里又沒用到構(gòu)造函數(shù),所以加不加應(yīng)該無所謂
2018-01-27
#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 = new student;
? ? // 設(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;
}
不需要括號的