将此类的引用传递给它的构造函数到指针C ++的向量

时间:2016-09-01 18:56:13

标签: c++ visual-studio pointers vector entity

好的,我有一个类型' Entity'的指针向量,我想要做的是,当一个新的Entity类型类被构造时,它被推回到实体的向量,在C#中可以通过传递这个'作为一个参数,在C ++中它没有给出任何错误,但是当我测试它时,向量并没有指向新构造的实体!

以下是一些代码:

' Public.h'和' Public.cpp'处理公共变量和函数,这里是指针向量和指针变量

vector <Entity*> AllEntities;
Entity* lastEntity;

这是类&#39;实体&#39;

的构造函数

&#39; Entity.cpp&#39;:

#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;
}

//其他代码

&#39; Entity.h&#39;不做什么,它只处理声明(或定义,不确定如何调用)变量和函数,如名称,标签和ID!

这是我的&#39; Main.cpp&#39;:

#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 =实体(&#34; ent1&#34;);

这里我创建了一个名为&#34; ent1&#34;的新实体,并自动为其提供标签&#34; Entity0&#34;和ID&#34; 0&#34;因为它是第一个实体!

  

ent1.PrintAll();

这是正常的,它打印出该实体的名称(&#34; ent1&#34;),标签和ID!

  

AllEntities.at(0) - &GT; PrintAll();

这基本上称为功能&#39; PrintAll&#39;来自第一个实体(在这种情况下是&#39; ent1&#39;),它应该打印相同的文本:&#39; ent1.PrintAll()&#39;但它没有,它打印:     (名称:&#34;&#34;标签:&#34;&#34;和ID:&#34;&#34;),我以为我没有正确使用矢量但是如下所示它没有& #39;也可以使用指针:

  

lastEntity-&GT; PrintAll();

这不起作用!

我不确定问题是什么,以及如何解决问题,首先我想的可能是变量:&#39;姓名&#39;和&#39;标记&#39;和&#39; ID&#39;不起作用,但问题是矢量并没有指向变量,我尝试过很多不同的功能,不仅仅是打印名称,但它没有&#t t&t #39;轨道&#39;创建的实体!

1 个答案:

答案 0 :(得分:1)

Entity ent1 = Entity("ent1");更改为Entity ent1("ent1")。这将正确构建您的对象。