3.67

来源:互联网 发布:土木工程用什么软件 编辑:程序博客网 时间:2024/06/07 17:38

3.6 的图为:


7:

(1)把第2行改为const Student stud(101.78.5)后,表明其为常对象,只能调用它的常成员函数,而不能调用它的普通成员函数,即chang函数不能使用,把display函数申明为常函数, 则可以用。

#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();    return 0;}
(2)若要使用chang函数, 而对象是常对象,则要用到mutable,把其声明为可变的数据,并且要使得chang函数可以调用, 需要加上const把它声明为常成员函数

#include <iostream>using namespace std;class Student {public:    Student(int n,float s):num(n),score(s){}    void change(int n,float s) const  {num=n;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;}
(3)用指向对象的指针变量也是可以的。

#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);    Student *p=&stud;    p->display();    p->change(101,80.5);    p->display();    return 0;}

(4)用指向常对象的指针变量也可以,结果一样。

(5)用指向对象的常指针变量也是一样的。





0 0