#include <vector>
using std::vector;
//base
class B
{
public:
int dataB = 0;
};
//Derived
class D : public B
{
public:
int dataD = 0;
};
class MyList
{
private:
// store some B or D or other objects Derived from B
// vector<B&> bList; // cant do this
vector<B> bList;
public:
void addB(B* newB, int newDataB)
{
// how to copy the data of newB, including dataB and dataD
// push_back(I don't know if this is right)
}
};
int main()
{
D d;
d.dataD = 1;
MyList myList;
myList.addB(&d, 1); //dont want d to be changed
myList.addB(&d, 2); //dont want d to be changed
return 0;
}
我想将数据从 d 复制到 myList 并更改新元素的 dataB,但不更改 d,我不知道该怎么做;
如果我在 addB 中这样做:
B* temp = new B(newB);
temp只会得到dataB,dataD被丢弃
而且我不能在 addB 中这样做:
D* temp = new D(newB);
因为不仅有D还有A或者C或者其他派生自B的类
使用 dynamic_cast 访问 myList 中的 dataD。
最佳答案
你不能存储D
s 在 std::vector<B>
.您只能存储 B
的拷贝D
的一部分.
您可以存储 D*
在std::vector<B*>
.尽管如果 vector 拥有,最好使用 std::unique_ptr<B>
#include <vector>
#include <memory>
//base
class B
{
public:
int dataB = 0;
};
//Derived
class D : public B
{
public:
int dataD = 0;
};
class MyList
{
private:
// store some B or D or other objects Derived from B
std::vector<std::unique_ptr<B>> bList;
public:
void addD(int dataB, int dataD)
{
bList.emplace_back(std::make_unique<D>(dataB, dataD));
}
};
int main()
{
MyList myList;
myList.addD(1, 1);
myList.addD(2, 1);
return 0;
}
如果您有很多派生自 B
的类,您可能需要一个模板将它们添加到 MyList
.
template<typename Derived, typename... Args>
void MyList::addDerived(Args... args)
{
bList.emplace_back(std::make_unique<Derived>(args...));
}
关于c++ - 关于继承和引用的C++问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58782095/