2013-09-30 51 views
0

继承问题,我有以下的结构,使我可以调用其中将包含一些Obj1Obj2Obj3Obj4vector<Obj<T>*>要素相同的功能。与指针定义

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

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

这种方法有什么好处吗?任何其他方式来实现这一目标?

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" 
+0

你没有显示真实的代码。 'std :: vector *> objs;'main()'中的''不会编译。 – Angew

+1

'a1'和'a2'从不初始化,这就是你所看到的随机数的原因。目前还不清楚你有什么样的问题,因为模板。你能展示你试图使用的静态定义吗? –

+0

Obj1,Obj2,Obj3,Obj4,Obj666 - **这是什么意思**?你想达到什么目的?看起来它可以在代码的<20% – sehe

回答

0

Obj1的构造函数不初始化a1任何东西。 DTTO为Obj2a2

+0

正确的,编辑和它的作品。耻辱导致我真正的代码有seg故障,我希望这一点代码将是原因。 – user2287453