阅读程序,分析输出结果。修改程序第2行为const Student stud(101,78.5),修改程序使之正常运行。

xiaoxiao2021-02-28  77

#include<iostream> using namespace std; class Student { public: Student(int n,float s):num(n),score(s){} void change(int n,float s){num=n;score=s;} void display(){cout<<num<<" "<<score<<endl;} private: int num; float score; }; int main() { Student stud(101,78.5); stud.display(); stud.change(101,80.5); stud.display(); return 0;

}

输出结果:

修改后的程序:

因为const Student stud(101,78.5);定义stud为常对象,不能修改常对象的数据成员,故change函数不能使用;

C++可以利用mutable声明想修改的数据成员,附上再次修改程序。

#include<iostream> using namespace std; class Student { public: Student(int n,float s):num(n),score(s){} //void change(int n,float s){num=n;score=s;} void display()const{cout<<num<<" "<<score<<endl;} private: int num; float score; }; int main() { const Student stud(101,78.5); stud.display(); //stud.change(101,80.5); stud.display(); return 0; }

再次修改:

#include<iostream> using namespace std; class Student { public: Student(int n,float s):num(n),score(s){} void change(int n,float s)const{score=s;} void display()const{cout<<num<<" "<<score<<endl;} private: mutable int num; mutable float score; }; int main() { const Student stud(101,78.5); stud.display(); stud.change(101,80.5); stud.display(); return 0; }

转载请注明原文地址: https://www.6miu.com/read-68749.html

最新回复(0)