简体   繁体   English

c ++将对象从一个类推到另一个类的向量中?

[英]c++ Pushing an object from one class into a vector in another class?

I'm fairly new to c++ programming and was wondering if someone could solve this one issue for me? 我是C ++编程的新手,想知道是否有人可以为我解决这个问题?

I'm going to use some examples for my question here. 我将在此处使用一些示例来回答我的问题。

Let's say that in my main class I create a Bob object from the Blue class, 假设在我的主类中,我从Blue类创建了一个Bob对象,

Blue Bob("bob", 3);

The Blue class takes a "name" and a size for the vector inside the class. Blue类具有一个“名称”和该类内部向量的大小。

Now let's introduce another class, Red, which takes four parameters and has three objects, 现在让我们介绍另一个类Red,它具有四个参数并具有三个对象,

Red GasPoweredStick("M000", "It never runs out of gas!", 1, 40);
Red Ozone("AFXE", "Filler", 4, 3);
Red Jupiter("KCAT", "Planets make terrible dinner guests", 99, 191919);

I want to add the Red objects to the vector in the Blue class under the Bob object, and then do things with those parameters, 我想将红色对象添加到Bob对象下的Blue类中的向量中,然后使用这些参数执行操作,

Bob.addItem(GasPoweredStick);
Bob.addItem(Ozone);
Bob.addItem(Jupiter);

which leads to this "addItem" code, 导致此“ addItem”代码,

void Blue::addItem(Red&)
{
    Items.push_back(Red());
}

I think my problem is at that above code...and the problem being that the parameter information from the Red objects default to their constructor's values, making them all blank or 0. instead of being filled with the information from the already created objects. 我认为我的问题在于上面的代码...问题是Red对象的参数信息默认为其构造函数的值,使它们全部为空白或0。而不是填充已创建对象的信息。 The reason as to why I can't solve this myself but got this far is because this is an assignment that I am working on, but my current education with c++ has not mentioned this particular problem. 之所以无法自己解决却无法解决的原因是因为这是我正在从事的一项工作,但是我目前对c ++的学习并未提及此特定问题。 The code is created from template or prior knowledge. 该代码是根据模板或先验知识创建的。

I don't have much experience with c++, but I'm guessing that the addItem function isn't taking in the three created objects but is instead copying the base Red class every time I asked it to push a new object. 我对c ++没有太多经验,但是我猜想addItem函数并没有吸收创建的三个对象,而是每次我要求它推送一个新对象时都复制基本Red类。

I would appreciate any help! 我将不胜感激任何帮助! I hope I was clear enough. 我希望我足够清楚。 I'll try to clear things up if they need to be. 如果需要的话,我会尽力清除。

This line: 这行:

Items.push_back(Red());

Your pushing back a newly created Red object using the default constructor. 您使用默认构造函数推回新创建的Red对象。 Just pass a reference: 只需传递参考即可:

void Blue::addItem(const Red& r)
{
    Items.push_back(r);
}

Your class Red should have a copying constructor and assignment operator: 您的Red类应具有复制构造函数和赋值运算符:

void Red::Red(const Red& other)
{
(*this) = other;
}

Red& Red::operator=(const Red& other)
{
this->Name = other.Name; 
// TODO: copy other fileds
return (*this);
}

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

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