我的自定义类
class Object {
public:
Object &operator=(const char *str) {
str_val_ = std::string(str);
return *this;
}
std::string str_val_;
};
我期望到达
int main() {
Object obj = "string";
// Is there a way to assign obj to string directly?
std::string str = obj;
}
我目前使用函数getValue()
来获取类中的确切字符串值
是否可以更改c++读取类的方式?
您正在寻找用户定义的转换函数:
Object::operator std::string() const
{
return str_val_;
}
然后可以将Object
强制转换为字符串:
std::string s = static_cast<std::stirng>(obj);
或者简单地说:
std::string s = obj;