c++ - 引用指针错误 : Non-const lvalue reference "const * FooBarClass" cannot bind to a temporary

标签 c++ pointers reference constants lvalue

FooClass.h:

class FooClass {
    .
    .
    .
    private:
        World *myWorld;
        const Player *&player;
    .
    .
    .
}

FooClass.cpp:

FooClass::FooClass(..., World *w) : myWorld(w), player(w->getPlayer())
{
    .
    .
    .
}

这会触发以下错误:对类型“const Player *”的非 const 左值引用无法绑定(bind)到类型“Player *”的临时值。然而 const Player * 类型的左值显然是一个 const 左值...

最佳答案

当我们谈论const 引用时,我们指的是它引用的类型是const

const Player *&player;

这个声明是一个引用。但是它引用的类型是 const 吗?不,这不对!它引用了一个指针,但该指针不是const。碰巧指针指向了 const 的东西,但这并没有使指针本身成为 const

要将引用绑定(bind)到临时值,您需要使引用成为const。所以你需要这个:

const Player * const &player;

但是,我无法想象您为什么想要这个。为什么需要引用 getPlayer 返回的临时值?当然,您只需要指针的拷贝:

const Player* player;

关于c++ - 引用指针错误 : Non-const lvalue reference "const * FooBarClass" cannot bind to a temporary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25796558/

相关文章:

c - 指针和字符

java - Java HashSet<String> 的 contains() 方法会测试字符串或对象标识的相等性吗?

pointers - Golang 通过引用结构成员值传递变量

c++ - 在 C++ 中定义离散概率分布

c++ - ignite C++ 客户端是否支持发布订阅

c - 使用 fgets() 从文件中读取多行并存储到指针数组

c# - 如何在 C# 中使用 Word 文档

c# - 有人能告诉我这个疯狂的 C++ 语句在 C# 中意味着什么吗?

c++ bool模板避免if语句

c - 指针变量存储什么?