代码重构尝试使用多态性和std::map
Code Refactoring Trying to use Polymorphism and std::map
我有这个类
struct B {
B( int x=0 ) { }
virtual void something() {
std::cout << "B()";
}
};
struct A {
B b;
int a;
A( int a, int b_ ) : a(a), b(b_) {a}
};
我已经实现了另一个C类
struct C : public B {
C( int x ) : B(b) { }
virtual void something() {
std::cout << "C()";
}
};
用C代替B得到A的最好方法是什么?
我已经试过了:
struct A {
B & b;
int a;
A( int a, B &b_ ) : a(a), b(b_) {a}
};
但是我必须使用std::map<int, A>
它给出了编译错误:
'A::A' : no appropriate default constructor available.
所以我做了这个:
struct A {
B & b;
int a;
A( int a=0, B &b_=B() ) : a(a), b(b_) {a}
};
在我的主中
std::map<int,A> mmap;
for( int i=0;i<5;++i ) {
auto & b = C();
mmap.insert( std::make_pair(i,A(i,b) ) ) ;
}
但是一旦CCD_ 2超出范围,mmap的A中的这些C的对象就变成了B。
它不起作用。如何修复?
在A构造函数中,您试图将B的临时实例分配给对B的引用,这是非法的。
你要做的是通过一个指向这个类的指针来更改这个引用:
#include <iostream>
#include <memory>
#include <map>
using namespace std;
struct B {
B( int x=0 ) { }
virtual void something()
{
std::cout << "B()";
}
};
struct A {
shared_ptr<B> b;
int a;
A( int a = 0, shared_ptr<B> b = shared_ptr<B>(new B()) ) : a(a), b(b) {}
};
struct C : public B {
C( int x ) { }
virtual void something()
{
std::cout << "C()";
}
};
int main()
{
shared_ptr<B> b = shared_ptr<B>( new C(0));
// Polymorphic test
b->something();
A a (0, b);
// map test
map<int, A> my_map;
my_map[0] = a;
return 0;
};
如果不能使用C++11,只需通过裸指针更改智能指针,并像往常一样正确处理动态内存。或者更好:使用Boost库,正如chris所提到的。
相关文章:
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- C++boost序列化多态性问题
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- 具有智能指针的多态性
- 在 C++ 中在堆栈上创建实例时如何保持多态性?
- 继承/多态性 - 我是否被迫使用"protected"变量?
- C++ 多态性在代码::块 17.12 中不起作用
- 复制STD :: sTD :: suolty_ptr带有多态性内容
- std :: remove_if多态性std :: std :: vector的simel_ptr
- std::vector 和/或多态性的问题
- std::可选和多态性
- 更改多态性boost :: shared_ptr(内部std :: vector)中的值
- 具有非成员功能的std::载体的多态性
- 代码重构尝试使用多态性和std::map
- c++ std容器-没有指针的多态性.这可能吗?
- c++11在使用std::thread时的意外多态性行为
- std::映射、多态性和删除