c++ - 这个 C++ 标识符是如何未定义的?

标签 c++ inheritance

好吧,我正在尝试学习 C++,我有两个对象,它们都是父类(“游戏”)的子类(“testgame”)。以下是两者的定义:

//game.h
#pragma once
#include <string>
class game
{
public:
    virtual ~game() {

    }
    virtual std::string getTitle() = 0;
    virtual bool setup() = 0;
    virtual void start() = 0;
    virtual void update() = 0;
};

和测试游戏

//testgame.h
#pragma once
#include "game.h"
#include <iostream>
class testgame :
    public game
{
public:
    std::string name;

    testgame(std::string name) {
        this->name = name;
    }
    ~testgame() {
        std::cout << name << " is being destroyed..." << std::endl;
        delete this;
    }
    bool setup() {
        std::cout << name << std::endl;
        return true;
    }
    void start() {
        std::cout << name << std::endl;
    }
    void update() {
        std::cout << name << std::endl;
    }
    std::string getTitle() {
        return name;
    }
};

现在,当我尝试这样做时:

#include "game.h"
#include "testgame.h"
...
game* game = new testgame("game1");
game* game2 = new testgame("game2");
...

game2 有一个错误,指出 game2 未定义。但是,如果我注释掉 game 的声明,错误就会消失。有人可以帮我弄清楚这里到底发生了什么吗?

最佳答案

一般来说,将变量命名为与类型相同会导致相当困惑的解析。

game* game = new testgame("game1");

现在 game 是一个值。所以不管你信不信,第二行解析为乘法。

(game * game2) = new testgame("game2");

这是可以理解的废话。因此,game2 是一个不存在的名称,我们正试图“乘以”它。只需将您的变量命名为 game1 或任何不是类型的名称即可。

关于c++ - 这个 C++ 标识符是如何未定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47520538/

相关文章:

c++ - (C++) 为什么 boost 作者在这里使用结构而不是类?

c++ - 编写此代码的更有效方法是什么?

php - 调用具有相同签名/名称的父函数

c++ - Netbeans C++ 尝试 make.exe 的相对路径

c++ - uint "representation"的内联 float 不起作用?

c++ - 如何让 Visual Studio 将所需的 .dll 文件复制到发布文件夹中?

c# - 多重继承

c++ - 如何使用 std::make_heap

C++ - 将两个子类的共同成员

Java动态创建未指定的类