c++ 之 const 修饰成员变量、成员函数

 const 修饰成员变量、成员函数

结论:

1、非const成员函数可以调用const成员函数,const成员函数不能调用非const成员函数。
2、非const成员函数、const成员函数可以任意访问const成员变量、普通变量。
3、const对象只可以调用const成员函数,非const对象任意调用成员函数。
class Student {
public:
    Student();
    Student(char *name, int age, float score);
    void show();
    //声明常成员函数
    char *getname() const;
    int getage() const;
    float getscore() const;
private:
    char *m_name;
    const int m_age;
    const float m_score;
};

Student::Student():m_age(4), m_score(566){
    m_name = new char[1000];
    m_name = const_cast<char*> ("sfsfgg");
}
Student::Student(char *name, int age, float score) : m_name(name), m_age(age), m_score(score) { }
void Student::show() {
    getage();      //非const成员函数调用const成员函数 
    std::cout << m_name << "的年龄是" << m_age << ",成绩是" << m_score << std::endl;
}
//定义常成员函数
char * Student::getname() const {
    return m_name;
}
int Student::getage() const {
    show();//非const成员函数调用const成员函数 
    return m_age;
}
float Student::getscore() const {
    return m_score;
}

int main()
{
    const Student ss;  //const对象调用非const成员函数 
    ss.show();

    Student ss0;  //非const对象调用const成员函数 
    ss0.getscore();
}

 

const 修饰指针容器

class AA
{
public:
    AA() { x = 0.1; };
    ~AA() {};
    int changeX() {
        x = 1512.0;
        return 0;
    }
public:
    double x;
};

std::vector<std::unique_ptr<AA>> ptrs;
const std::vector<std::unique_ptr<AA>>& getptr() {
    ptrs.push_back(std::make_unique<AA>());
    return ptrs;
}

int main() {

    const auto & pts = getptr();
    pts[0]->changeX();

    std::cout << "x:: " << pts[0]->x <<"\n";
    return 0;
}

 

posted @ 2022-11-03 15:01  玥茹苟  阅读(83)  评论(0编辑  收藏  举报