烟台网站搜索优化,创意个人网站设计,交互 网站,页脚修改设计 wordpress主题C 中#xff0c;const 也可以用来修饰对象#xff0c;称为常对象。一旦将对象定义为常对象之后#xff0c;就只能调用类的 const 成员#xff08;包括 const 成员变量和 const 成员函数#xff09;了。
定义常对象的语法和定义常量的语法类似#xff1a;
const class …C 中const 也可以用来修饰对象称为常对象。一旦将对象定义为常对象之后就只能调用类的 const 成员包括 const 成员变量和 const 成员函数了。
定义常对象的语法和定义常量的语法类似
const class object(params);class const object(params);定义 const 指针
const class *p new class(params);class const *p new class(params);class为类名object为对象名params为实参列表p为指针名。两种方式定义出来的对象都是常对象。
一旦将对象定义为常对象之后不管是哪种形式该对象就只能访问被 const 修饰的成员了包括 const 成员变量和 const 成员函数因为非 const 成员可能会修改对象的数据编译器也会这样假设C禁止这样做。
常对象使用举例
#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(){coutm_name的年龄是m_age成绩是m_scoreendl;
}
char * 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(); //errorcoutstu.getname()的年龄是stu.getage()成绩是stu.getscore()endl;const Student *pstu new Student(李磊, 16, 80.5);//pstu - show(); //errorcoutpstu-getname()的年龄是pstu-getage()成绩是pstu-getscore()endl;return 0;
}stu、pstu 分别是常对象以及常对象指针它们都只能调用 const 成员函数。