【问题标题】:convert user-defined type to std::string in C++在 C++ 中将用户定义的类型转换为 std::string
【发布时间】:2014-10-01 13:20:41
【问题描述】:

如果我有一个用户定义的类型,例如:

 typedef std::string GenderType;
 GenderType gender;

是否可以将gender 设置为等于std::string 变量?

 std::string temp;
 temp = gender;

我是否需要以某种方式从GenderType 中提取std::string?使用stringstream 这样做更安全吗?

【问题讨论】:

  • typedef 引入了同义词,同一类型的另一个名称。换句话说,std::string 和 GenderType 的意思完全一样。
  • 是的,它导致了崩溃,并且我的调试器无法工作 b/c 我的 pdb 文件超过 1GB 哈哈
  • GenderType 只是std::string 的别名有什么问题?
  • 我不会认为 typedef 是用户定义的类型。 class、stuct 和 union 声明用户定义的类型。 typedef 只是现有类型的别名。
  • @squareskittles 如果您的应用程序崩溃,这不是因为为 std::string 引入了类型别名,而是几乎可以肯定是因为我们在您的上述帖子中看不到的其他内容。从软件工程的角度来看:std::string 对于GenderType 来说是一个糟糕的选择。 enum 可能更适合。

标签: c++ stringstream stdstring user-defined-types


【解决方案1】:

使用typedef 定义类型别名,即这两种类型是相同的。没有办法区分这两种类型。您可以在任何可以使用另一种的地方使用一种。

所以

GenderType gender;
std::string temp;
temp = gender;

与

相同
std::string gender, temp;
temp = gender;

使用类型别名,您无法添加任何类型安全性。

【讨论】:

    猜你喜欢
    • 2011-03-31
    • 2012-06-10
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 2022-01-03
    • 2016-01-04
    相关资源
    最近更新 更多