const函数的编译器错误

Nav*_*een 1 c++ const

我不确定我是否遗漏了一些基本的东西.但我无法理解为什么编译器会为此代码生成错误:

class A
{
};

class B
{
public:
    B();
    A* get() const;

private:
    A* m_p;
};

B::B()
{
    m_p = new A;
}

A* B::get() const
{
    //This is compiling fine
    return m_p;
}

class C
{
public:
    A* get() const;
private:
    A m_a;
};

A* C::get() const
{
   //Compiler generates an error for this. Why? 
    return &m_a;
}
Run Code Online (Sandbox Code Playgroud)

编辑:编译器错误是:错误C2440:'return':无法从'const class A*'转换为'class A*'转换失去限定符

Kon*_*lph 12

const在函数签名中告诉编译器可能不会修改对象的成员.然而,您返回const指向成员的非指针,从而允许违反该承诺.

在你的类中B,由于你没有返回指向成员的指针而你没有做出任何承诺,你返回它的副本(并且成员恰好是指针).