c++ - 通过 const 成员变量访问内联函数

标签 c++ constants inline member-functions const-cast

我想了解内联成员变量在通过 const 成员变量访问它时如何工作。 每次我尝试这样做时,都会收到错误!

这就是我正在尝试的

#include <iostream>
#include <string>
using namespace std;

class A{
    public:
    A()
    {
        _uuid = 0;
    }
    ~A();
    void setUUID(int n) { _uuid = n; }
    inline int getUUID(){  return _uuid;} const
    int getUUID1() const {  return _uuid;} 
    int getUUIDsmart()const 
    { 
        return _uuid; 
    }
    private:
    int _uuid;    
};

class B {
    public:
    B(){}
    ~B();
    void fun1(const A *obj) 
    {
        cout<<obj->getUUIDsmart()<<endl;   //works fine
        cout<<obj->getUUID1()<<endl;       //works fine
        cout<<obj->getUUID()<<endl;        //error

        A *obj1 = const_cast<A *>(obj);
        cout<<obj1->getUUID()<<endl;       //works fine
    }
};

int main()
{
  B *b = new B;
  A *a = new A;
  a->setUUID(12);
  b->fun1(a);
}

我能够让我的代码工作

const_cast

但我有兴趣知道,如果我尝试通过 const 成员函数访问内联函数,为什么会出现错误?

更新:修复

我的错。我把 const 的位置弄乱了! 感谢@bruno

inline int getUUID() const { return _uuid; }
//correct syntax. i placed the const at the end

最佳答案

[注意:我使用问题的第一个版本]

你的 const 位置错误:

inline int getUUID(){  return _uuid;} const
int getUUID1(){  return _uuid;} const
int getUUIDsmart()const 

事实上

inline int getUUID(){  return _uuid;} 
const int getUUID1(){  return _uuid;} 
const int getUUIDsmart()const 

出于可读性原因,我刚刚将 const 移到了右行

你想要

inline int getUUID() const {  return _uuid;}
int getUUID1() const{  return _uuid;}

在您的版本中,getUUID1getUUID 都不是 const,因此您无法将它们应用于 const 实例

与您的方法是否内联这一事实根本没有任何联系。


注意:

cout<<obj->getUUID1()<<endl;       //works fine

没有

关于c++ - 通过 const 成员变量访问内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54826507/

相关文章:

c++ - 强制编译时检查正确的对象实例化

c++ - 指向 const 的指针可以指向非常量对象 - 语言设计或技术原因?

c++ - 我的 C++ 内联方法是否应该显式声明为内联?

c - 是否可以仅通过某些调用内联函数

c++ - 如何将值列表传递给需要数组的函数?

c++ - 结构中的模板结构问题 -

c++ - 从 C++ 中的 const 成员函数修改引用成员

c++ - 输入迭代器必须具有 const 解引用运算符吗?

C++ const 函数错误

javascript - Cckeditor:按需显示和隐藏内联工具栏