[英]pass the reference of this class inside it's constructor to a vector of pointers C++
好的,所以我有一個類型為'Entity'的指針向量,而我想做的是,當構造一個新的Entity類型類時,它被推回到Entities的向量中,在C#中,可以通過傳遞'this'來實現作為參數,在C ++中不會給出任何錯誤,但是當我對其進行測試時,矢量不會指向新構造的Entity!
這是一些代碼:
'Public.h'和'Public.cpp'處理公共變量和函數,這是指針向量和指針變量
vector <Entity*> AllEntities;
Entity* lastEntity;
這是“實體”類的構造函數
'Entity.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();
//其他代碼
實體ent1 = Entity(“ ent1”);
在這里,我創建了一個名稱為“ ent1”的新實體,由於它是第一個實體,它會自動為其賦予標簽“ Entity0”和ID“ 0”!
ent1.PrintAll();
這可以正常工作,它會打印出該實體的名稱(“ ent1”),標簽和ID!
AllEntities.at(0)-> PrintAll();
這基本上是從第一個實體(在本例中為“ ent1”)中調用函數“ PrintAll”,它應該打印與此相同的文本:“ ent1.PrintAll()”,但不會,它打印:(名稱:“”,標簽:“”,ID:“”),我以為我沒有正確使用向量,但如下圖所示,它也不適用於指針:
lastEntity-> PrintAll();
這行不通!
我不確定是什么問題,以及如何解決它,首先我想也許是關於變量的一些東西:“名稱”,“標簽”和“ ID”不起作用,但問題是向量不起作用。指向變量,我嘗試了很多不同的功能,不僅使用了打印名稱,而且還沒有“追蹤”所創建的實體!
更改Entity ent1 = Entity("ent1");
到Entity ent1("ent1")
。 這將正確構造您的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.