【发布时间】:2020-08-27 12:58:56
【问题描述】:
如何让一个类在被调用时返回一个成员变量?说:
class Person {
std::string name;
// Constructor and Destructor go here..
};
Person mike = "Mike";
// /!\ How do you make "mike" return "Mike" directly when the object mike is called?
// This is the same thing like an int return its value and a vector returns its members (scalars)
std::string name = mike;
附加编辑:强制转换运算符在这里不是一个好选择,因为它破坏了类型的编写方式。例如std::string name = static_cast<string>(mike); 是实现我的目标的可怕方式。
【问题讨论】:
-
听起来您正在寻找"cast operator"?
-
@0x5453 Python中没有类似“repr”的东西吗?我不是 Python 方面的专家,但我认为这种方法实现了我正在尝试做的事情。
-
Python 和 C++ 是两种不同的语言。 C++ 有自己的一套范式、习语和规则。
-
@xxdraxulis 你总是可以重载
to_string(const Person&)或operator<<(std::ostream&, const Person&),但它们的行为与Python 的__repr__不太一样。 -
考虑隐式转换的代价是(不那么明显)。突然之间,在需要
std::string的情况下,使用Person不会出现编译器错误。转换是有意的还是逻辑错误?现在由你决定,编译器不再提供帮助