简体   繁体   English

C ++字符串成员变量不存在于向量中

[英]C++ string member variable not present in vector

I am creating a vector that contains pointers to a base class. 我正在创建一个包含指向基类的指针的向量。 In this vector I'm dynamically storing pointers to derived classes which contain some member variables, one of them being a string variable name. 在这个向量中,我动态存储指向派生类的指针,派生类包含一些成员变量,其中一个是字符串变量名。

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>

bool hasDirection = false;
bool hasDiameter = false;
int direction;
float diameter;
int starDimension = 0;
int animalDimension = 0;
int fishDimension = 0;
 class MovingObject
{
protected:
    std::string name;
    int direction;
    float diameter;
    int dimension;
    float movingSpeed;

public:
    std::string getName(){ return name;};
    int getDirection(){ return direction;};
    float getDiameter(){ return diameter;};
    float getMovingSpeed(){ return movingSpeed;};
    int getDimension(){ return dimension;};
    void setName(std::string v){ name = v;};
    void setDirection(int d){ direction = d;};
    void setDiameter(float f){ diameter = f;};
    void setMovingSpeed(float s){ movingSpeed = s;};
    void setDimension (int d){ dimension = d;};
    virtual void PrintContents()=0;
};

static std::vector<MovingObject*> data;

class starObject : public MovingObject
{
public:
    void PrintContents()
    {
        std::cout << "(" << getName() << "," << getDiameter() << "," << getDirection() << ")";
    }
};

class animalObject : public MovingObject
{
public:
    void PrintContents()
    {
        std::cout << "(" << getName() << "," << getDiameter() << "," << getDirection() << ")";
    }
};

class fishObject : public MovingObject
{
public:
    void PrintContents()
    {
        std::cout << "(" << getName() << "," << getDiameter() << "," << getDirection() << ", [" << getDimension() << "], " << getMovingSpeed() << ")";
    }
};

I later set all these member variables inside a main function. 我后来在主函数中设置了所有这些成员变量。 The problem is when I try to output the contents of the member variables, all of them show up except for the string name. 问题是当我尝试输出成员变量的内容时,除了字符串名称之外,它们都会显示出来。 Now, I've checked to make sure that the string gets set before calling the PrintContent() method, and it shows that the value is in the vector. 现在,我已经检查过以确保在调用PrintContent()方法之前设置字符串,并且它显示该值在向量中。 However, when I debug through the code, the value is no longer there, instead containing an empty string. 但是,当我通过代码调试时,该值不再存在,而是包含一个空字符串。

Could someone with better c++ knowledge explain to me why this is happening? 有更好的c ++知识的人可以向我解释为什么会这样吗? This is the main class: 这是主要类:

int main()
{
        std::string type;
        Reader reader;

        while (!std::cin.eof())
        {
            try
            {
                std::string type;
                std::cin >> type;

                if (type =="int")
                {
                    reader.ReadDirection();
                }
                else if (type =="float")
                {
                    reader.ReadDiameter();
                }
                else if (type == "string")
                {
                    std::string name;
                    std::cin >> name;

                    if (hasDirection && hasDiameter)
                    {
                        int dimension;
                        if (diameter > 0 && diameter < 10)
                        {   
                            //fish
                            fishObject fish;
                            fish.setName(name);
                            fish.setDiameter(diameter);
                            fish.setDirection(direction);

                            dimension = fishDimension;
                            fishDimension += 50;
                            fish.setDimension(dimension);
                            fish.setMovingSpeed(0.1);
                            data.push_back(&fish);
                        }
                        else if (diameter >= 10 < 500)
                        {
                            //animal
                            animalObject animal;
                            animal.setName(name);
                            animal.setDiameter(diameter);
                            animal.setDirection(direction);

                            dimension = animalDimension;
                            animalDimension += 800;
                            animal.setDimension(dimension);
                            animal.setMovingSpeed(5.0); 
                            data.push_back(&animal);
                        }
                        else if (diameter >=500)
                        {
                            //star
                            starObject star;
                            star.setName(name);
                            star.setDiameter(diameter);
                            star.setDirection(direction);

                            dimension = starDimension;
                            starDimension += 5000;
                            star.setDimension(dimension);
                            star.setMovingSpeed(30.0);
                            data.push_back(&star);
                        }

                    }
                    else
                    {
                        throw (IncompleteData(name));
                    }
                }
            }
            catch (IncompleteData e)
            {
                std::cerr << "No diameter or direction given for object " << e.objectName << "\n";
            }
        }

The objects you push to the data vector are local because they are declared inside if/else blocks (see the declarations of fish and animal ). 您推送到data向量的对象是本地的,因为它们是在if / else块中声明的(请参阅fishanimal的声明)。

When you push the address of such an object to the vector, it will continue to point to the local object, which ceases to exist at the end of the local scope. 当您将此类对象的地址推送到向量时,它将继续指向本地对象,该对象在本地范围的末尾不再存在。 You need to create objects that live beyond the local scope. 您需要创建超出本地范围的对象。 One way of doing this is to create copies of the local objects on the heap and push those to the vector: 执行此操作的一种方法是在堆上创建本地对象的副本并将其推送到向量:

data.push_back(new fishObject(fish));

Of course this means that you get a memory leak unless you make sure you explicitly delete the elements of the vector some time before the end of the program. 当然,这意味着您会遇到内存泄漏,除非您确保在程序结束前的某个时间显式删除了向量的元素。 The usual recommendation to avoid having to think of this is to use a vector of std::unique_ptr<MovingObject> instead of a vector of naked pointers. 避免不得不考虑这个的通常建议是使用std::unique_ptr<MovingObject>的向量而不是裸指针的向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM