调用常量成员与普通成员函数(P119)

/*

常量成员和常引用成员

由关键字const修饰的类成员变量称为类的常量成员变量

     类的常量成员变量必须进行初始化,而且只能通过构造函数的成员初始化列表的方式进行。(常引用型成员变量相同)

使用const修饰的函数称为常量函数
const 数据类型 常量名 =表达式;
定义类的对象前添加const关键字,则该对象称为常量对象
类型说明符 函数名(参数表)const;

*/

#include<iostream>
using namespace std;

class Sample
{
public:
Sample();
void getValue()const;
void getValue();
void priValue();
void priVcon()const;
};

Sample::Sample(){}
void Sample::getValue()const
{
cout<<"常量成员函数"<<endl;
}

void Sample::getValue()
{
cout<<"非常量成员函数"<<endl;
}

void Sample::priValue()
{
cout<<"非常量成员函数"<<endl;
}

void Sample::priVcon()const
{
cout<<"常量成员函数"<<endl;
}

int main()
{
const Sample cono;
Sample o;
cout<<"cono\t";
cono.getValue(); //通过常量对象可以调用常量成员函数
//cono.priValue(); //错误!不能调用非常量成员函数
cout<<"o\t";
o.priValue(); //通过普通对象调用
cout<<"o\t";
o.priVcon();
return 0;
}

posted @ 2020-03-07 13:37  CollisionDimension  阅读(288)  评论(0)    收藏  举报