[英]Redefining class member data types
Is it possible to change the data type of a class member after its initialization? 初始化后是否可以更改类成员的数据类型? Say, redefine a double named "Foo" to a string? 说,重新定义一个名为“ Foo”的双精度字符串?
No. Types are fixed at compile time. 否。类型在编译时是固定的。 If you want to switch between double and a string perhaps reach for a std::variant : 如果要在双精度字符串和字符串之间切换,则可以达到std :: variant :
std::variant<double, std::string> val = 1.0;
val = std::string("hello");
As answer to your comment, you should use std::optional
作为您的评论的答案,您应该使用std::optional
std::optional<int> Do(int x, int y)
{
if ( x == y )
{
return 42;
}
return {};
}
int main()
{
auto ret = Do(3,2); // << exchange your test data here!
if ( ret )
{
std::cout << "Got an answer" << ret.value() << std::endl;
}
else
{
std::cout << "No answer" << std::endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.