C++ 左值需要作为一元“&”操作数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6879749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:49:00  来源:igfitidea点击:

C++ lvalue required as unary '&' operand

c++

提问by grouse

I'm working on a game engine and working on implementing a state design. I have an Engine class which takes care of all the initialization of everything and contains the game loop which calls update, render and handle input functions of the active state.

我正在研究游戏引擎并致力于实现状态设计。我有一个 Engine 类,它负责所有内容的所有初始化,并包含调用更新、渲染和处理活动状态输入函数的游戏循环。

All my different states inherit from State which requires a reference to the Engine class in its constructor, in order to initialize the protected reference of the engine for future use. Here's the relevant code:

我所有的不同状态都继承自 State,它需要在其构造函数中引用 Engine 类,以便初始化引擎的受保护引用以备将来使用。这是相关的代码:

// file: state.h
class Engine;

class State {
public:

    State(Engine &engine) : mEngine(engine) { }
protected:
    Engine &mEngine;
};

// file: gamestate.h
class GameState : public State {
public:
    GameState(Engine &engine) : State(engine) {}
};

and finally in engine.cpp in the initializer I create a new GameState object, which is where the error is reported.

最后在初始值设定项中的 engine.cpp 中,我创建了一个新的 GameState 对象,这是报告错误的地方。

GameState *state = new GameState(&this);

I'm coding it in C++ using Qt Creator on Linux at the minute, don't have access to a windows machine right now to see if it's a problem with the gcc or not.

我现在正在 Linux 上使用 Qt Creator 用 C++ 编码它,现在无法访问 Windows 机器来查看它是否是 gcc 的问题。

回答by user258808

Change:

改变:

 GameState *state = new GameState(&this);

to:

到:

GameState *state = new GameState(*this);

This is because you are passing the Engine by reference to the constructor of the State class.

这是因为您通过引用 State 类的构造函数来传递 Engine。