0

我有以下结构,以便我可以在vector<Obj<T>*>其中包含一些Obj1Obj2或的元素上调用相同Obj3的函数Obj4

Obj3并且Obj4由其他对象(1 和 2)定义,它们需要在 const Obj1 或 const Obj2 上调用这些函数。

问题在于Obj666,pObj 似乎没有指向o1_unit. 我会static Obj1<double> = o1_unit(Obj1<double>(1.0))在 Obj3 中声明和定义 a 并将该指针传递给它,但我不能因为模板。

那个方法好用吗?还有其他方法可以实现这一目标吗?

template <typename T>
class Obj   
{
    public:
    T a;

    public:
    Obj(T a_ = 0) : a(a_) {}

    virtual void fun() const = 0;

};

template <typename T>
class Obj1 : public Obj<T>
{
    public:
    T a1;

    public:
    // Obj1(T a1) : Obj<T>(a1) {} EDIT
    Obj1(T a1_) : Obj<T>(a1_), a1(a1_) {} 
    void fun() const
    { std::cout << a1 << std::endl;}
};

template <typename T>
class Obj2 : public Obj<T>
{
    public:
    T a2;

    public:
//  Obj2(T a2) : Obj<T>(a2) {}   EDIT
Obj2(T a2_) : Obj<T>(a2_), a2(a2_) {}

    void fun() const
    { std::cout << a2 << std::endl;}
};

template <typename T>
class Obj666 : public Obj<T>
{
    public:
    Obj<T> *pObj; // need pointers because Obj3 uses an Obj1 but other subclasses could use Obj2 ...
    T a666;

    public:
    Obj666(Obj<T>* pO) : Obj<T>(0), pObj(pO) {}
    Obj666(Obj<T>* pO, T a666_) : Obj<T>(0), pObj(pO), a666(a666_) {}

    virtual void fun() const
    { pObj->fun();
        std::cout << a666 << std::endl; 
    }

};

template <typename T>
class Obj3 : public Obj666<T>
{
    public:
    Obj3() : Obj666<T>(&o1_unit), o1_unit(Obj1<T>(1.0)) {}
    Obj3(T a666_) : Obj666<T>(&o1_unit, a666_), o1_unit(Obj1<T>(1.0)) {}

    void fun() const
    { (this->pObj)->fun();
        std::cout << "and something else from Obj3" << std::endl;
    }

    public:
        Obj1<T> o1_unit; // Obviously, I would do without it, but I can't declare a static Obj1<T> o1_unit = Obj1<T>(1.0), because template..
};

template <typename T>
class Obj4 : public Obj666<T>
{
    public:
    Obj4() : Obj666<T>(&o2_unit), o2_unit(Obj2<T>(10.0)) {}
    Obj4(T a666_) : Obj666<T>(&o2_unit, a666_), o2_unit(Obj2<T>(10.0)) {}

    void fun() const
    { (this->pObj)->fun();
        std::cout << "and something else from Obj4" << std::endl;
    }

    public:
        Obj2<T> o2_unit; // Obviously, I would do without it, but I can't declare a static Obj1<T> o1_unit = Obj1<T>(1.0), because template..

};

/// main.cpp
Obj3<double> o3(5);
Obj4<double> o4(13);

std::vector<Obj<T>*> objs;

objs.push_back(&o3);
objs.push_back(&o4);

objs[0]->fun(); // I'd like to call o1_unit->fun() so result 1 and 10
objs[1]->fun(); // but I have random numbers (2.0887e-317, 6.95324e-310 ..)
                // Same if I remove Obj3->fun, it calls Obj666->fun, but still no "1"
4

1 回答 1

0

的构造函数Obj1不初始化a1任何东西。DTTOObj2a2.

于 2013-09-30T10:16:08.793 回答