C++:常量函数示例

本文探讨了C++中的常量函数,重点讲解如何使用常对象和常对象指针调用const成员函数,以确保对象状态的不可变性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常对象以及常对象指针,它们都只能调用 const 成员函数。

// const_example.cpp : 定义控制台应用程序的入口点。
//常对象使用举例:

#include "stdafx.h"
#include <iostream>
using namespace std;

class Student{
public:
	Student(char *name, int age, float score);		//初始化函数
public:
	void show();
	char *getname() const;
	int getage() const;
	float getscore() const;
private:
	char *m_name;
	int m_age;
	float m_score;


};

Student::Student(char *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;
}
char *Student::getname() const
{
	return m_name;
}
int Student::getage() const
{
	return m_age;
}
float Student::getscore() const
{
	return m_score;
}

//stu、pstu分别是常对象以及常对象指针,它们都只能调用 const 成员函数。

int _tmain(int argc, _TCHAR* argv[])
{
	const Student stu("小明", 15, 90.6);
	//stu.show();  //error,常量对象只能访问常量函数。
	cout << stu.getname() << "的年龄是
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值