代码重构尝试使用多态性和std::map

Code Refactoring Trying to use Polymorphism and std::map

本文关键字:std 多态性 map 重构 代码      更新时间:2023-10-16

我有这个类

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所提到的。