此C 标识符如何未定义

How is this C++ identifier undefined?

本文关键字:未定义 标识符      更新时间:2023-10-16

好的,所以我正在尝试学习C ,并且我有两个对象的父级(" testgame")的两个对象(" testgame")(" game")。这是两者的定义:

//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

//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或任何类型的任何东西,它将奏效。