常对象以及常对象指针,它们都只能调用 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() << "的年龄是