C++ c++;指向其他类对象的指针向量(使用随机指针归档)
我有几个类有共同的父类。子类可以包括其他子类的实例,其中C++ c++;指向其他类对象的指针向量(使用随机指针归档),c++,C++,我有几个类有共同的父类。子类可以包括其他子类的实例,其中first\u Child类具有second\u Child类的实例,second\u Child类具有third\u Child类的实例。这样,当您创建first\u child对象实例时,它还包含second\u child类的对象实例,该类还包含third\u child类的对象实例。 由于我的项目的性质,第一个对象中的所有对象对于父类的公共参数必须具有相同的值。所以为了避免硬编码,我在父类中添加了指向parent\u类的指针向量。该
first\u Child
类具有second\u Child
类的实例,second\u Child
类具有third\u Child
类的实例。这样,当您创建first\u child
对象实例时,它还包含second\u child
类的对象实例,该类还包含third\u child
类的对象实例。由于我的项目的性质,第一个对象中的所有对象对于父类的公共参数必须具有相同的值。所以为了避免硬编码,我在父类中添加了指向
parent\u类的指针向量。该向量由指向对象构造函数中所有子对象的指针填充,并通过循环设置所需的公共参数。简化示例如下所示:
parent.h
class Parent_class{
public:
std::string name = "";
int val = 0;
std::vector<Parent_class *> SUB;
Parent_class();
void setSub();
void printSub();
};
_
_
_
_
_
当我尝试执行以下操作时,问题出现了:
First f = First();
f.setSub();
f
中的SUB
向量和f.SECOND
的大小应为1
,但f.SECOND中的SUB
向量。第三个没有大小0
,而是一些随机大数(如18446744073709024152
中的大)。
有人能向我解释一下为什么会发生这种情况,以及是否有可能在不将SECOND
和THIRD
声明为指向对象的指针的情况下实现这一点?我希望避免使用指针,因为据我所知,在销毁第一个实例时,所有子对象(SECOND
,THIRD
,…)都会被销毁 假设向量的唯一目的是设置公共参数,那么整个方法就是过于复杂,毫无意义,您可以通过虚拟setter函数实现同样简单得多的功能:
class Parent
{
int _x; // the common parameter...
public:
int x() { return _x; }
virtual void x(int value) { _x = value; }
// ^^^^^^^ (!)
};
class First : public Parent
{
Second _second;
public:
void x(int value) override
// ^^^^^^^^ (!)
{
Parent::x(value);
_second.x(value);
}
};
Second
类似地
first.cpp
#include "first.h"
first.cpp
First::First() {
name = "first";
SECOND = Second();
SUB.push_back(&SECOND);
}
second.h
#include "parent.h"
#include "third.h"
class Second : public Parent_class {
public:
Second();
Third* THIRD;
};
second.cpp
#include "second.h"
Second::Second() {
name = "second";
THIRD = new Third();
SUB.push_back(&THIRD);
}
third.h
#include "parent.h"
class Third : public Parent_class{
public:
Third();
};
third.cpp
#include "third.h"
Third::Third() {
name = "third";
SUB.clear();
}
First f = First();
f.setSub();
class Parent
{
int _x; // the common parameter...
public:
int x() { return _x; }
virtual void x(int value) { _x = value; }
// ^^^^^^^ (!)
};
class First : public Parent
{
Second _second;
public:
void x(int value) override
// ^^^^^^^^ (!)
{
Parent::x(value);
_second.x(value);
}
};