C++常量对象、常量成员函数

发布时间:2019-06-21 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了C++常量对象、常量成员函数脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

为什么要有这玩意

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

定义

常量对象

#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;
}
// const Vector<int> v;
// v[0] = 0; // v[0]返回的是const int &,不能被修改
template<class T>
const T &Vector<T>::operator[](Rank r) const {
    return _elem[r];
}

// Vector<int> v;
// v[0] = 0; // v[0]返回的是int &,可修改
template<class T>
T &Vector<T>::operator[](Rank r) {
    return _elem[r];
}

脚本宝典总结

以上是脚本宝典为你收集整理的C++常量对象、常量成员函数全部内容,希望文章能够帮你解决C++常量对象、常量成员函数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。