当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

C++常量对象、常量成员函数 - 人工智能之路

作者:小梦 来源: 网络 时间: 2024-03-30 阅读:

为什么要有这玩意

创建一个不能被修改的对象,还可以做些事情

定义

常量对象

  • 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;}

热点阅读

网友最爱