一个关于继承和引用的C++问题
a C++ question about inheritance and reference
#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>
中。您只能存储D
的B
部分的副本。
可以将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;
}
相关文章:
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- Xcode 语义问题引用或以前定义的代码
- C++ 关于指针取消引用的技术问题
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 棘手的按值传递和按引用递归问题传递
- 当我尝试通过 arduino 上的引用传递布尔数组时出现问题
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 取消引用向量时出现问题
- 有关从C++中的不同源文件引用类的问题
- C++:取消引用十六进制值,有点语法问题
- 运行veins_inet示例 - 未定义的引用的 Omnet++ 问题
- C++ - 对 PCM::getInstance() 的未定义引用问题
- 通过键入的引用问题传递函数
- 一个关于继承和引用的C++问题
- 关于引用数组位置的问题
- printf(时差程序)中的引用问题
- 无法取消引用超出范围的向量迭代器 - 有什么问题?
- "Field has incomplete type"引用自己的类的问题
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 使用 opencv 和 C++ - 未定义的引用的链接器出现问题