好的,所以我有一个“实体”类型的指针 vector ,我想做的是,当构造一个新的实体类型类时,它会被推回实体 vector ,在 C# 中,这可以通过传递'this' 作为参数,在 C++ 中它没有给出错误,但是当我测试它时, vector 不指向新构造的实体!
这是一些代码:
'Public.h'和'Public.cpp'处理公共(public)变量和函数,这里是指针 vector 和指针变量
vector <Entity*> AllEntities;
Entity* lastEntity;
这是“实体”类的构造函数
'实体.cpp':
#include "Public.h"
#include "Entity.h"
// constructor
Entity::Entity(string name, string tag)
{
ID = GetCounter();
this->Name = UniqueName(name);
this->Tag = UniqueTag(tag);
AllEntities.push_back(this); // it doesn't give any errors
lastEntity = this; // because i thought it was a problem with the vector i tried the same with a variable, but it doesn't work too
}
// Function that prints the name, tag, and id.
void Entity::PrintAll(){
cout << "NAME: \"" << Entity::Name << "\" TAG: \"" << Entity::Tag << "\" ID: \"" << Entity::ID << "\"" << endl;
}
//其他代码
'Entity.h' 做的不多,它只处理变量和函数的声明(或定义,不确定它是如何调用的),如 Name、Tag 和 ID!
这是我的“Main.cpp”:
#include "SFML\Graphics.hpp"
#include "SFML\System.hpp"
#include "Public.h"
#include "DisplayText.h"
#include "SaySomething.h"
// note that i'm including 'Entity.h' through 'Public.h' with Include Guards so i won't get any linker errors !
int main()
{
// sfml stuff !
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
Entity ent1 = Entity("ent1");
ent1.PrintAll();
AllEntities.at(0)->PrintAll();
lastEntity->PrintAll();
//其他代码
Entity ent1 = Entity("ent1");
我在这里创建了一个新实体,名称为“ent1”,它自动为它赋予标签“Entity0”和 ID“0”,因为它是第一个实体!
ent1.PrintAll();
这工作正常,它打印出这个实体的名称(“ent1”),标签和 ID!
AllEntities.at(0)->PrintAll();
这基本上从第一个实体(在本例中为“ent1”)调用函数“PrintAll”,它应该打印与此相同的文本:“ent1.PrintAll()”但它没有,它打印: (名称:“”,标签:“”和 ID:“”),我以为我没有正确使用 vector ,但如下所示,它也不适用于指针:
lastEntity->PrintAll();
这行不通!
我不确定问题是什么,以及如何解决它,首先我想可能是关于变量的一些事情:'Name' 和 'Tag' 和 'ID' 不起作用,但问题是vector 不指向变量,我尝试了很多不同的函数,不仅是打印名称,而且它不会“跟踪”创建的实体!
最佳答案
将 Entity ent1 = Entity("ent1");
更改为 Entity ent1("ent1")
。这将正确构建您的对象。
关于c++ - 将此类在其构造函数中的引用传递给指针 vector C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39278954/