C++常量对象、常量成员函数 - 人工智能之路
为什么要有这玩意
创建一个不能被修改的对象,还可以做些事情
定义
常量对象
const 对象 变量名;
必须手动创建构造函数,否则成员变量将永远都是垃圾值
#include <iostream>#include <stdio.h>using namespace std;class Person {public: string name; Person() { name = "haha"; }};int main() { const Person person; return 0;}
常量成员函数
不能调用非常量成员函数,因为调用的函数可能会修改对象
静态成员变量和函数,可以随意调用,因为它们本质上不属于某个类
void sayHello() const { cout << "Hello" << endl;}
示例
#include <iostream>#include <stdio.h>using namespace std;class Person {public: string name; Person() { name = "haha"; } // 修改对象的函数,不能加const void setName(string name) { this->name = name; } void sayHello() const { cout << "Hello" << endl; // 常量成员函数不能调用非常量成员函数,因为调用的函数可能会修改对象 // setName("hehe"); }};int main() { const Person person; // 定义一个常量对象// person.name = "hehe"; // 不能位于等号左边// person.setName("hehe"); // 常量对象不能调用非常量成员函数 person.sayHello(); string name = person.name; cout << name << endl; return 0;}
常量成员函数的重载
#include <iostream>#include <stdio.h>using namespace std;class Person {public: Person() {} void sayHello() { cout << "Hello" << endl; } void sayHello() const { cout << "const Hello" << endl; }};int main() { const Person p1; Person p2; p1.sayHello(); // 常量对象调用常量成员函数 p2.sayHello(); // 正常的对象调用没常量成员函数 return 0;}