函数声明后面的const用法

来源:互联网 发布:32bit安装tensorflow 编辑:程序博客网 时间:2024/04/30 14:27

在类成员函数的声明和定义中,

const的函数不能对其数据成员进行修改操作。

const的对象,不能引用非const的成员函数。

#include <stdio.h>#include <string.h>#include <iostream.h>class A{    private:        int m_a;    public:         A() : m_a(0) {}         int getA() const  { return m_a; //同return this->m_a; }         int GetA() { return m_a; }         int setA(int a) const        {                m_a = a; //这里产生编译错误,如果把前面的成员定义int m_a;改为mutable int m_a;就可以编译通过。       }          int SetA(int a)          { m_a = a; //同this->m_a = a;  }}; int main()  {           A a1;      const A a2;       int t;        t = a1.getA();        t = a1.GetA();        t = a2.getA();       // t = a2.GetA(); //a2是const对象,调用非const成员函数产生编译错误。        return 1;  }  


0 0
原创粉丝点击