如果把類中的初始化函數(shù)也注釋就會正常打印數(shù)值了,這是怎么回事呢?
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class Student
{
public:
???? void setName(string _name)
???? {
??????? m_strName=_name;
???? }
???? string getName()
???? {
???????? return m_strName;
???? }
???? void setGender(string _gender)
???? {
???????? m_strGender = _gender;
???? }
???? string getGender()???? {
???????? return m_strGender;
???? }
??? ?
???? int getScore()
???? {
???????? return m_iScore;
???? }
??? ?
???? /*void initScore()
???? {
???????? m_iScore = 0;
?????? ?
???? }
????? * */
??? ?
???? void study (int _score)
???? {
???????? m_iScore += _score;
???? }
private:
string m_strName;
string m_strGender;
int m_iScore;
};
int main()
{
??? Student stu;
??? //stu.initScore();
??? stu.setName("z");
??? stu.setGender("f");
??? stu.study(5);
??? stu.study(5);
?? ?
??? cout <<? stu.getName() << " " << stu.getGender() << " " << stu.getScore() << endl;
??? return 0;
}
1.沒有明白為什么沒有初始化,score的值不正常,有study 函數(shù)來賦值呢。
stu.study(5);
void study (int _score)
???? {
???????? m_iScore += _score;
???? }
2.? 把類中的初始化函數(shù)也注釋就會正常打印數(shù)值了,這是怎么回事呢?
2017-03-07
你問題問的不是很清楚,大概解釋一下,類中的數(shù)據(jù)成員如果沒有初始化,不同的編譯器在分配內(nèi)存空間會自動賦值,這個值有的編譯器是0,有的編譯器是一個隨機數(shù)(一般是一個很大的數(shù)),所以跟study函數(shù)沒有關(guān)系,以為m_iScore已經(jīng)被賦值了。你的編譯器應(yīng)該是自動賦值為0,所以沒有初始化函數(shù)也會正常打印數(shù)值,但如果再換一個編譯器就不一定了。