成员函数中const使用方法小结(一)

来源:互联网 发布:破解版直播软件 编辑:程序博客网 时间:2024/06/11 02:15

#include<iostream>#include<string>using namespace std;/*如果一个对象通过引用方式传递到函数f中,而函数f又不会改变该对象的数据成员,那么最好在传递的这个参数前加上const*/class Student{private:int age;public:void setName(const int &age);/*如果一个成员函数不需要直接或间接地改变该函数所属对象的任何数据成员,因此将get标记为const*/int getName() const ;int getName2();int getName3() const;};void Student::setName(const int &age){this->age = age;}/*int Student::getName() const {return this->age;}*/int Student::getName2() {return this->age;}int Student::getName3() const{return this->age;}/*int Student::getName() const {return this->getName2();/*错误,const成员函数只能调用const成员函数,因为非const成员函数可能会改变对象的成员数据*/}*/int Student::getName() const{return this->getName3();}int main(){Student s;s.setName(23);cout << s.getName() << endl;return 0;}


原创粉丝点击