page contents

C++中 const对象用法

在 C++ 中,const 也可以用来修饰对象,称为常对象。一旦将将对象定义为...

在 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++禁止这样做。


常对象使用举例:






  1. #include <iostream>

  2. using namespace std;

  3. class Student{

  4. public:

  5. Student(char *name, int age, float score);

  6. public:

  7. void show();

  8. char *getname() const;

  9. int getage() const;

  10. float getscore() const;

  11. private:

  12. char *m_name;

  13. int m_age;

  14. float m_score;

  15. };

  16. Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }

  17. void Student::show(){

  18. cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;

  19. }

  20. char * Student::getname() const{

  21. return m_name;

  22. }

  23. int Student::getage() const{

  24. return m_age;

  25. }

  26. float Student::getscore() const{

  27. return m_score;

  28. }

  29. int main(){

  30. const Student stu("小明", 15, 90.6);

  31. //stu.show();  //error

  32. cout<<stu.getname()<<"的年龄是"<<stu.getage()<<",成绩是"<<stu.getscore()<<endl;

  33. const Student *pstu = new Student("李磊", 16, 80.5);

  34. //pstu -> show();  //error

  35. cout<<pstu->getname()<<"的年龄是"<<pstu->getage()<<",成绩是"<<pstu->getscore()<<endl;

  36. return 0;

  37. }

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

attachments-2021-04-PYWfQJlR606d8c9d98463.jpg

  • 发表于 2021-04-07 18:46
  • 阅读 ( 580 )
  • 分类:C/C++开发

0 条评论

请先 登录 后评论
小柒
小柒

1312 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1312 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章