[英]C++ Operator overloading: assign A's attribute value of type B to a B object
The std::string class allows assigning its internal value from different types, such as 'char', 'const char*' and 'std::string', with the help of this operator. std :: string类允许在此运算符的帮助下,从不同类型(例如'char','const char *'和'std :: string')分配其内部值。 Which operator is needed to be overloaded in order to achieve the following?
为了实现以下目标,需要重载哪个运算符?
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;
};
After that, we should be able to access std::string's functions through the A object, for example: 之后,我们应该能够通过A对象访问std :: string的函数,例如:
A a("foo");
printf("A's value: %s \n", a.c_str());
You need to make it possible for class A
to convert itself to type string
. 您需要使
class A
将自身转换为string
类型。
This looks like: 看起来像:
class A
{
public:
operator std::string() const { return m_value; }
};
After that, you can do this: 之后,您可以执行以下操作:
printf("A's value: %s \n", ((std::string)a).c_str());
Alternately, you can overload the ->
operator: 或者,您可以重载
->
运算符:
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.