C++运算符重载:将A的B类型的属性值赋值给B对象
C++ Operator overloading: assign A's attribute value of type B to a B object
std::string class 允许在 'char'、'const char*' 和 'std::string' 等不同类型中分配其内部值,借助 this 运算符。需要重载哪个运算符才能达到以下目的?
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());
std::string class 允许在 'char'、'const char*' 和 'std::string' 等不同类型中分配其内部值,借助 this 运算符。需要重载哪个运算符才能达到以下目的?
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());