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

为何要有这玩意

建立一个不能被修改的对象,还能够作些事情ios

定义

常量对象

  • const 对象 变量名;函数

  • 必须手动建立构造函数,不然成员变量将永远都是垃圾值this

#include <iostream>
#include <stdio.h>

using namespace std;

class Person {
public:
    string name;
    Person() {
        name = "haha";
    }
};

int main() {
    const Person person;
    return 0;
}

常量成员函数

  • 不能调用很是量成员函数,由于调用的函数可能会修改对象spa

  • 静态成员变量和函数,能够随意调用,由于它们本质上不属于某个类code

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];
}
相关文章
相关标签/搜索