例1-2 get函数返回私有变量指针有问题吗
#include<iostream> #include<cstring> using namespace std; class Account{ private: int ID; char Name[20]; float balance; public: void Initial(int ID,char Name[],float balance); int withdraw(float m); void deposits(float m); char *getname(){ return Name; } void setName(char*name){ strcpy(Name,name); } void showme(){ cout<<Name<<" "<<balance<<endl; } }; void Account::Initial(int ID,char Name[],float balance) { this->ID=ID;//因为名称相同,所以要用this指针来访问 strcpy(this->Name,Name); this->balance=balance; } int Account::withdraw(float m) { if(balance>m){balance=balance-m;return 1;} else return -1; } void Account::deposits(float m) { balance=balance+m; } int main() { Account my,other; char name[]="Jack"; my.Initial(10112,name,600.0); my.withdraw(500.0); my.showme(); char*p=my.getname();//获取了私有变量的指针 strcpy(p,"abc");//直接0修改了私有变量的内容 my.showme(); return 0; }
never give up
浙公网安备 33010602011771号