C++ 运算符重载:将 A 的类型 B 的属性值分配给 B 对象
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());
IDEOne link
相关文章:
- 将数组的地址分配给变量并删除
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 如何通过一个循环将多个文件的内容分配给不同的类属性?
- 属性分配无效:"displayText"是文本字段 qml 中的只读属性
- 动态分配的属性和继承
- 使用 switch 语句将不同的函数作为类属性分配 C++
- 从多属性<< C,B> 分配变体A,B,C>?
- 分配以下对象属性在哪里
- 将成员函数分配给实例成员的属性
- 使用 QAbstractListModel 分配 QML 布尔属性失败
- QML 无法分配给不存在的属性
- 在运行时分配已发布属性的确切时间?
- 为什么我不能分配此QT属性
- boost :: Spirit属性分配:struct is_nullary:基本类型无法成为结构或类型
- 如何避免为未使用的属性分配内存
- c++中对象属性的内存分配
- Qt - 无法分配给不存在的属性(自定义C++类)
- QML 无法将分配shared_ptr分配给<Track> [未知属性类型]
- 如何使具有常量属性的类可分配
- GLSL 3.30之前的属性分配