从模板继承:作用域错误



这是我的代码:

#include<stdarg.h>
#include<deque>
using namespace std;
template<typename T,int dim>
class trj:public deque<T>{
public:
    void push_back(T,...);
    virtual void set_calculate_method(int)=0;
};                                                
template<typename T,int dim>                      
class bb:public trj<T,dim>{                             
public:                                                                           
    void set_calculate_method(int);                                    
};
template<typename T,int dim>                
void trj<T,dim>::push_back(T in,...){   
    va_list ap;                         
    T aux;                              
    va_start(ap,in);                    
    aux=in;                             
    deque<T>::push_back(new T[dim]);    
    for(int i=0;i<dim;i++){             
        *(deque<T>::back()+i)=aux;      
        aux=va_arg(ap,T);               
    }                                                                  
    va_end(ap);                         
}                                       
int main(){                                               
    bb<double,3> t;                                       
    t.push_back(2,3,4);                                                                   
    return 0;                                             
}                                                         

我有这个编译错误

uno.cpp: In member function ‘void trj<T, dim>::push_back(T, ...) [with T = double, int dim = 3]’:
uno.cpp:57:   instantiated from here
uno.cpp:16: error: no matching function for call to ‘trj< double, 3 >::push_back(double*)’
/usr/include/c++/4.4/bits/stl_deque.h:1201: note: candidates are: void std::deque <_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = double, _Alloc = std::allocator<double>]
uno.cpp:57:   instantiated from here
uno.cpp:18: error: invalid type argument of ‘unary *’

为什么编译器会发出" un. cpp:16: error: no matching function for call to ' trj<Double,>::push_back(Double *)" if我写了"deque:: push_back方法(新T[的]);"在那一行?"

因为deque<T>::push_back期望一个const引用,而你传递的是一个非const指针。

我不能确定,但我认为你只是想做一个deque<T>::resize和通过dim

deque<T>::push_back想要T,而不是T的数组。

顺便说一下,我强烈反对从deque派生,因为它的析构函数是非虚的。如果某些代码通过指向基类的指针删除类的实例,则会得到未定义的行为。

最新更新