2013-04-14 99 views
0

時,我得到了以下錯誤:聊齋志異「的非const引用無效初始化」使用模板

Database.hpp: In member function ‘Table<T, S>& Table<T, S>::operator=(const Table<T, S>&) [with T = int, int S = 3, Table<T, S> = Table<int, 3>]’: 
Database.hpp:40:8: instantiated from ‘void std::vector<_Tp, _Alloc>::_M_insert_aux(std::vector<_Tp, _Alloc>::iterator, const _Tp&) [with _Tp = List, _Alloc = std::allocator<List>, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<List*, std::vector<List> >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = List*]’ 
/usr/include/c++/4.6/bits/stl_vector.h:834:4: instantiated from ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = List, _Alloc = std::allocator<List>, std::vector<_Tp, _Alloc>::value_type = List]’ 
SelectiveReading.hpp:139:34: instantiated from here 
Database.hpp:34:16: error: invalid initialization of non-const reference of type ‘Table<int, 3>&’ from an rvalue of type ‘Table<int, 3>* const’ 

我有以下的抽象數據類型。我不明白他們有什麼問題。

// this is Database.hpp 
template <class T, int S> 
class Table 
{ 
    T tab[S]; 
    public: 
    inline T& operator[](int i) 
    { 
     return tab[i]; 
    } 
    inline const T& operator[](int i) const 
    { 
     return tab[i]; 
    } 
    Table() {} 
    ~Table() {} 
    Table(const Table &t) 
    { 
     for (int i=0; i<S; ++i) 
     { 
      tab[i] = t[i]; 
     } 
    } 
    Table& operator=(const Table &t) 
    { 
     for (int i=0; i<S; ++i) 
     { 
      tab[i] = t[i]; 
     } 
     return this; 
    } 
}; 

typedef Table<int,3> Date; 

struct List 
{ 
    Date AnnouncementDate; 
    int BonusShares; 
    int StockSplit; 
    int CashDividend; 
    bool DividendPayment; 
    Date ExDividendDate; 
    Date ShareRecordDate; 
    Date BonusSharesListingDate; 
}; 

typedef std::vector<List> Database; 

雖然電話是這樣的:

List record; 
// (...) 
Data.push_back(record); // this is SelectiveReading.hpp:139:34 

回答

6

在你operator=的最後一行,你是返回this(指針),當你的意思是返回*this(參考)。

相關問題