2014-04-03 96 views
1

以下代碼有什麼問題。因爲如果我在主函數內定義類,編譯失敗,我不理解編譯器錯誤。在函數中定義的結構/類編譯錯誤

測試從here

評論的drift_f的第一定義(外的main())的代碼並取消的drif_t內定義(main()函數內)和編譯器將得到以下錯誤消息:

prog.cpp: In function ‘int main()’: 
prog.cpp:27:24: error: template argument for ‘template<class> class std::allocator’ uses local type ‘main()::drift_t’ 
     std::deque<drift_t> drift; drift.push_back(drift_t(0,0));drift.push_back(drift_t(-50,-50)); 
         ^
prog.cpp:27:24: error: trying to instantiate ‘template<class> class std::allocator’ 
prog.cpp:27:24: error: template argument 2 is invalid 
prog.cpp:27:31: error: invalid type in declaration before ‘;’ token 
     std::deque<drift_t> drift; drift.push_back(drift_t(0,0));drift.push_back(drift_t(-50,-50)); 
          ^
prog.cpp:27:39: error: request for member ‘push_back’ in ‘drift’, which is of non-class type ‘int’ 
     std::deque<drift_t> drift; drift.push_back(drift_t(0,0));drift.push_back(drift_t(-50,-50)); 
            ^
prog.cpp:27:69: error: request for member ‘push_back’ in ‘drift’, which is of non-class type ‘int’ 
     std::deque<drift_t> drift; drift.push_back(drift_t(0,0));drift.push_back(drift_t(-50,-50)); 

#include <iostream> 
#include <deque> 
using namespace std; 

    class drift_t{ //It works 
     public: 
     int _drift; 
     int _immediateDrift; 
     drift_t() : _drift(0), _immediateDrift(0) {} 
     drift_t(int d, int expected) : _drift(d), _immediateDrift(expected) {} 
     drift_t(const drift_t& ro) : _drift(ro._drift), _immediateDrift(ro._immediateDrift) {} 
     drift_t& operator = (const drift_t& ro) { this->_drift = ro._drift; this->_immediateDrift = ro._immediateDrift; return *this; } 
     } ;//*/ 

int main() { 

    /*class drift_t{ //It doesn't works 
     public: 
     int _drift; 
     int _immediateDrift; 
     drift_t() : _drift(0), _immediateDrift(0) {} 
     drift_t(int d, int expected) : _drift(d), _immediateDrift(expected) {} 
     drift_t(const drift_t& ro) : _drift(ro._drift), _immediateDrift(ro._immediateDrift) {} 
     drift_t& operator = (const drift_t& ro) { this->_drift = ro._drift; this->_immediateDrift = ro._immediateDrift; return *this; } 
     } ;//*/ 

    std::deque<drift_t> drift; drift.push_back(drift_t(0,0));drift.push_back(drift_t(-50,-50)); 
    return 0; 
} 
+0

它在這裏編譯得很好。編譯器的錯誤信息是什麼? –

+0

你使用C++ 11嗎?此代碼爲我編譯:http://coliru.stacked-crooked.com/a/c27b407705349ae9 –

+0

我在工作站上使用Ideone和4.6.3下的GCC C++ 4.8.1。兩者都有相同的結果。查看我最後的編輯瞭解更多詳情。 – alexbuisson

回答

1

是不是編譯器說的錯誤?您不能使用本地類進行該模板初始化。

嘗試使用-std = C++ 11進行編譯,因爲我相信它會放鬆一下。

相關問題