C++ const成员变量、成员函数和对象

const成员变量

const成员变量和const普通变量用法相似。初始化const成员变量只有一种方法,就是通过构造函数的初始化列表。

const成员函数

const成员函数可以使用类中的所有成员变量,但是不能修改它们的值。

注意:const成员函数需要在声明和定义的时候在函数头部的结尾加上const关键字

函数开头的const用来修饰函数的返回值,表示返回值是const类型,也就是不能被修改。
函数头部的结尾加上const表示常成员函数,这种函数只能读取成员变量的值,而不能修改成员变量的值。

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对象

常对象:只能调用类的const成员(包括const成员变量和const成员函数)

#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;
}

猜你喜欢

转载自www.cnblogs.com/xiaobaizzz/p/12348254.html