C ++ const member variables, member functions and objects

const member variables

const const member variables and common variables similar usage. Const member variable initialization is only one method is to list initialized by the constructor.

const member functions

const member functions can be used in all members of the class variables, but can not modify their values.

Note: const member functions need to declare and define the time at the end of the function header plus the const keyword

Const function used to modify the beginning of the function return value, the return value is expressed const type, i.e. can not be modified.
Plus the head end of the function often represent const member functions, this function can only read the value of a member variable, but can not change the value of a member variable.

class Student{
public:
    Student(string name, int age, float score);
    void show();
    //声明常成员函数
    string getname() const;
    int getage() const;
    float getscore() const;
private:
    string m_name;
    int m_age;
    float m_score;
};
Student::Student(string name, int age, float score): m_name(name), m_age(age), m_score(score){ }
void Student::show(){
    cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
//定义常成员函数
string Student::getname() const{
    return m_name;
}
int Student::getage() const{
    return m_age;
}
float Student::getscore() const{
    return m_score;
}

const object

Often the object: const member can only call the class (including const const member variables and member functions)

#include<iostream>
#include<string>
using namespace std;

class Student{
public:
    Student(string name, int age, float score);
public:
    void show();
    string getname() const;
    int getage() const;
    float getscore() const;
private:
    string m_name;
    int m_age;
    float m_score;
};
Student::Student(string name, int age, float score): m_name(name), m_age(age), m_score(score){ }
void Student::show(){
    cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
string Student::getname() const{
    return m_name;
}
int Student::getage() const{
    return m_age;
}
float Student::getscore() const{
    return m_score;
}
int main(){
    const Student stu("小明", 15, 90.6);
    //stu.show();  //error
    cout<<stu.getname()<<"的年龄是"<<stu.getage()<<",成绩是"<<stu.getscore()<<endl;
    const Student *pstu = new Student("李磊", 16, 80.5);
    //pstu -> show();  //error
    cout<<pstu->getname()<<"的年龄是"<<pstu->getage()<<",成绩是"<<pstu->getscore()<<endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/xiaobaizzz/p/12348254.html