【发布时间】:2020-03-29 18:03:00
【问题描述】:
我想将std::string 自动转换为我的类型my_type,定义为
typedef std::pair<std::string,int> my_type;
使得转换后的my_type 的.first 部分是字符串,而.second 部分始终为0。
如果调用函数std::string fun(my_type x, ...) { return x.first; } 时也应该可以使用,比如说,
std::string s = "Hello"; fun(s, ...);.
我不想定义一个新类来代替my_type,并且如果可能的话也不想重载我的所有函数。我试图围绕如何使用 operator 来解决这个问题,但我无法编译我的程序。
编辑: 由于如果不定义自定义结构左右这似乎是不可能的,这是我想出的一种解决方法,但我希望它可以在不定义新类/结构的情况下实现。不过,感谢您为我节省了更多尝试执行此操作的时间。
class Element {
public:
Element() {};
Element(std::string s, int a) { name = s; value = a; };
Element(std::string s) { name = s; value = 0; };
...
std::string return_name() { return name; };
private:
std::string name;
int value;
};
std::string fun(Element x) { return x.return_name(); };
现在可以自动调用std::string s = "Hello"; fun(s);。
【问题讨论】:
-
做不到。寻找解决方法。
-
您需要重载或使用转换运算符创建自己的类型。这些是唯一的选择。
-
“隐式类型转换”是一个矛盾。强制转换是您在源代码中编写的内容,用于告诉编译器进行转换。它总是明确的。您想要的术语是“隐式转换”。