C++ const对象

C++ const对象教程

C++ 中,const 也可以用来修饰 对象,使用 const 修饰的对象称为常对象。一旦将对象定义为常对象之后,就只能调用类的 const 成员变量 或者 const 成员函数 了。

C++ const对象详解

定义

使用 const 修饰的对象,称为常对象。

语法

const ClassName var1(params); ClassName const var2(params);

说明

我们使用 const 定义常对象,const 可以放在类型的前面也可以放在类型的后面。

案例

C++ const对象

使用 const 定义常对象,常对象只可以访问常成员

#include <iostream> using namespace std; class Student { public: Student(string name, int age) { this->m_name = name; this->m_age = age; } void sayHello() const { cout << "I am " << this->m_name << " and i am " << this->m_age << " years old!" << endl; } void show() { cout << "Call Show" << endl; } private: string m_name; int m_age; }; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; const Student stu("HaiCoder", 111); stu.sayHello(); return 0; }

程序运行后,控制台输出如下:

34_C const成员.png

我们使用 const 定义了一个常对象,接着,我们使用该常成员调用了常成员函数 sayHello,此时,程序正常,现在,我们修改程序如下:

#include <iostream> using namespace std; class Student { public: Student(string name, int age) { this->m_name = name; this->m_age = age; } void sayHello() const { cout << "I am " << this->m_name << " and i am " << this->m_age << " years old!" << endl; } void show() { cout << "Call Show" << endl; } private: string m_name; int m_age; }; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; const Student stu("HaiCoder", 111); stu.show(); return 0; }

程序运行后,控制台输出如下:

35_C const成员.png

这次,我们使用了常对象调用了非常成员函数,结果,程序报错,因为,常对象只能访问常成员。

C++ const对象教程总结

在 C++ 中,const 也可以用来修饰对象,使用 const 修饰的对象称为常对象。一旦将对象定义为常对象之后,就只能调用类的 const 成员变量或者 const 成员函数了。