![](/img/trans.png)
[英]C++ Overloading assignment operator: “cannot convert `B*` to `A*`” error
[英]C++ Operator overloading: assign A's attribute value of type B to a B object
std :: string类允许在此运算符的帮助下,从不同类型(例如'char','const char *'和'std :: string')分配其内部值。 为了实现以下目标,需要重载哪个运算符?
class A {
public:
A(std::string value)
: m_value(value)
{
}
// A a = std::string("some value")
A& operator=(const std::string value) {
m_value = value;
}
// std::string someValue = A("blabla")
???? operator ????
private:
std::string m_value;
};
之后,我们应该能够通过A对象访问std :: string的函数,例如:
A a("foo");
printf("A's value: %s \n", a.c_str());
您需要使class A
将自身转换为string
类型。
看起来像:
class A
{
public:
operator std::string() const { return m_value; }
};
之后,您可以执行以下操作:
printf("A's value: %s \n", ((std::string)a).c_str());
或者,您可以重载->
运算符:
class A
{
public:
const std::string* operator->()const { return & m_value; }
}
printf("A's value: %s \n", a->c_str());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.