好吧,所以我正在尝试学习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;
};
Run Code Online (Sandbox Code Playgroud)
和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;
}
};
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试这样做时:
#include "game.h"
#include "testgame.h"
...
game* game = new testgame("game1");
game* game2 = new testgame("game2");
...
Run Code Online (Sandbox Code Playgroud)
game2有错误说game2未定义.但是,如果我评论出来game的声明,那么错误就会消失.有人可以帮我弄清楚究竟发生了什么吗?
通常,与类型相同的命名变量将导致相当混乱的分析.
game* game = new testgame("game1");
Run Code Online (Sandbox Code Playgroud)
现在game是一个价值.所以第二行解析为,信不信由你,乘法.
(game * game2) = new testgame("game2");
Run Code Online (Sandbox Code Playgroud)
这是可以理解的废话.因此,game2是一个不存在的名称,我们试图通过它"乘".只需命名您的变量game1或任何非类型的东西,它就会成功.