一个关于继承和引用的C++问题

a C++ question about inheritance and reference

本文关键字:问题 引用 继承 C++ 于继承 一个      更新时间:2023-10-16
#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将只获得数据B,数据D将被丢弃

并且我不能在addB:中执行此操作

D* temp = new D(newB);

因为从B 中不仅有D,还有A或C或其他类别

使用dynamic_cast访问myList中的dataD。

不能D存储在std::vector<B>中。您只能存储DB部分的副本。

可以D*存储在std::vector<B*>中。尽管如果矢量拥有,最好使用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...));
}

从您的详细信息中很难理解具体的问题。正如我所理解的。这可以为你工作

#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)
(*newB).dataB = newDataB;
bList.push_back(*newB);
}
};
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;
}