类中int数组为什么不能正确访问?该怎么解决
类中int数组为什么不能正确访问?
结果为什么是:
****************s2.score[0]= 10
****************s2.score[1]= -858993460
****************s2.score[2]= 4201565
Press any key to continue
------解决方案--------------------
int* student::getScore() const{
int sc[3] = {0};
for(int i=0; i<3; i++)
sc[i] = this->score[i];
return sc;
}
这样不行吧,sc是一个局部变量,函数返回时,内存地址被释放
------解决方案--------------------
- C/C++ code
#include <string> #include <iostream> using namespace std; class student{ private: string name; int score[3]; int sum; public: student(int s[], string name= ""); student(const student& s); ~student(){ /*delete score;*/ }; int* getScore() const; int getSum() const; string getName() const; student& operator=(const student& s); bool operator==(const student& s); bool operator<(const student& s); }; student::student( int sc[], string n):name(n),sum(0){ for(int i=0; i<3; i++){ score[i] = sc[i]; sum += sc[i]; } } int* student::getScore() const{ int sc[3] = {0}; for(int i=0; i<3; i++) sc[i] = this->score[i]; return sc; } void main(){ int sc2[3] = {10,20,30}; student s2(sc2, "赵"); int* temp; temp = s2.getScore(); for(int i=0; i<3; i++){ cout << "****************s2.score[" << i << "]= " << temp[i] <<endl; } }
结果为什么是:
****************s2.score[0]= 10
****************s2.score[1]= -858993460
****************s2.score[2]= 4201565
Press any key to continue
------解决方案--------------------
int* student::getScore() const{
int sc[3] = {0};
for(int i=0; i<3; i++)
sc[i] = this->score[i];
return sc;
}
这样不行吧,sc是一个局部变量,函数返回时,内存地址被释放
------解决方案--------------------
- C/C++ code
#include <string> #include <iostream> using namespace std; class student{ private: string name; int score[3]; int sum; public: student(int s[], string name= ""); student(const student& s); ~student(){ /*delete score;*/ }; const int* getScore() const; int getSum() const; string getName() const; student& operator=(const student& s); bool operator==(const student& s); bool operator<(const student& s); }; student::student( int sc[], string n):name(n),sum(0){ for(int i=0; i<3; i++){ score[i] = sc[i]; sum += sc[i]; } } const int* student::getScore() const{ return score; } int main(){ int sc2[3] = {10,20,30}; student s2(sc2, "赵"); const int* temp; temp = s2.getScore(); for(int i=0; i<3; i++){ cout << "****************s2.score[" << i << "]= " << temp[i] <<endl; } return 0; }