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

const成员函数想要改变成员变量的值怎么办?

方法1:在成员变量前加mutable

#include<iostream>
using namespace std;

class student{
	mutable int m_age;
public:
	void fun(int age) const;
};

void student::fun(int age) const{
	m_age = age;
	cout << m_age << endl;
}

int main(){
	student stu;
	stu.fun(10);
	return 0;
} 

方法2:创建一个const指针指向this指针所指的对象,然后用这个指针去操作想要修改的成员变量

#include<iostream>
using namespace std;

class student{
	mutable int m_age;
public:
	void fun(int age) const;
};

void student::fun(int age) const{
	student* p = const_cast<student*>(this); //this是const指针 
	p -> m_age = age;
	cout << m_age << endl;
}

int main(){
	student stu;
	stu.fun(10);
	return 0;
} 

原文链接: https://www.cnblogs.com/xiaobaizzz/p/12348254.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/193483

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午6:23
下一篇 2023年2月12日 下午6:23

相关推荐