2014-11-24 92 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