如何从"const tm&"制作"const tm*"?
How can I make a 'const tm*' from a 'const tm&'?
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&"制作"const tm*"?
static_cast<const tm*>(getTM())
你当然不希望一个static_cast<>
(也不是一个reinterpret_cast<>
)来做这件事!
请参阅std::asctime()
的参考,它实际上想要一个指针:
char* asctime( const std::tm* time_ptr );
// ^
"我怎样才能从'const tm&'制作'const tm*'?"
你的函数返回一个const &
,这不是一个指针。更改代码以传递结果的地址:
asctime ( &getTM() );
// ^ <<<< Take the address of the result, to make it a const pointer
查看完整的现场演示。
您可能也有兴趣阅读此问答:
在C++中,指针变量和引用变量有什么区别?