2014-11-24 90 views
2
namespace abc{ 
    class MyClass{ 
    protected: 
     tm structTime; 
    public: 
     const tm& getTM(){ 
      return structTime; 
     } 
     void foo(){ std::string tmp = asctime (this->getTM()); } 
    }; 

上面的代碼給了我這個錯誤:如何從'const tm&'創建'const tm *'?

error: cannot convert 'const tm' to 'const tm*' for argument '1' to 'char* asctime(const tm*)' 

然後我改變了代碼,以這樣的:

std::string tmp = asctime (static_cast<const tm*>(getTM())); 

但是這給了我一個錯誤,指出:

invalid static_cast from type 'const tm' to type 'const tm*' 

如何從'const tm'創建'const tm *''?

回答

3

static_cast<const tm*>(getTM())

肯定不希望一個static_cast<>(也不是reinterpret_cast<>)要做到這一點!

std::asctime()參考,就是了指示器實際上:

char* asctime(const std::tm* time_ptr); 
         //^

"How can I make a 'const tm*' from a 'const tm&'?"

你的函數返回一個const &,這不是一個指針。更改您的代碼傳遞結果的地址:

asctime (&getTM()); 
     //^<<<< Take the address of the result, to make it a const pointer 

看到一個完整的LIVE DEMO


您還可能有興趣在閱讀這個問答&答:

What are the differences between a pointer variable and a reference variable in C++?

+0

是的,你說得對! – Jamiil 2014-11-26 03:14:09

+0

@Jamiil _「是的,你說得對!」_你有沒有考慮接受答案呢?這可能有助於未來的研究人員判斷問答對有幫助。 – 2014-11-26 18:06:50

+0

@Jamiil這也將支持避免愚蠢的功能請求[像這樣](http://meta.stackoverflow.com/questions/277918/should-users-with-high-rep-be-able-to-accept-answers出現在MSO上的問題與不接受問題。 – 2014-11-26 18:21:17