如何从'const tm&'中创建'const tm *'?

时间:2014-11-24 18:18:07

标签: c++

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

上面的代码给了我这个错误:

 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&amp;'中创建'const tm *'?

1 个答案:

答案 0 :(得分:3)

  

static_cast<const tm*>(getTM())

当然不希望 static_cast<>(也不是reinterpret_cast<>)来执行此操作!

请参阅std::asctime()的参考资料,它实际上需要一个指针:

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

&#34;我如何制作一个&#39; const tm *&#39;来自&#39; const tm&amp;&#39;?&#34;

你的函数返回const &,它不是指针。更改代码以传递结果的地址:

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

查看完整的 LIVE DEMO


您可能也有兴趣阅读此Q&amp; A:

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