重载运算符=,用于类中的结构
Overloading operator= for structs, within classes
我们有以下内容:(伪)
class MyClass
{
private:
struct MyStruct{
MyStruct operator=(const MyOtherStruct& rhs);
int am1;
int am2;
};
};
我们想重载 MyClass 中的 =
运算符.cpp执行以下操作:
MyStruct&
MyStruct::operator=(const MyOtherStruct& rhs)
{
am1 = rhs.am1;
am2 = rhs.am2;
}
但是,它不想编译。我们收到类似于
"失踪 ;之前 &"
和
"MyStruct 必须是类或命名空间,如果后跟 ::"
这里有我缺少一些概念吗?
您需要将
MyStruct
operator=
移动到结构声明正文中:
class MyClass
{
private:
struct MyStruct{
int am1;
int am2;
MyStruct& operator=(const MyOtherStruct& rhs)
{
am1 = rhs.am1;
am2 = rhs.am2;
return *this;
}
};
};
或者,如果由于MyOtherStruct
不完整或不想弄乱类声明而无法做到这一点:
class MyClass
{
private:
struct MyStruct{
int am1;
int am2;
MyStruct& operator=(const MyOtherStruct& rhs);
};
};
inline MyClass::MyStruct& MyClass::MyStruct::operator=(const MyOtherStruct& rhs)
{
am1 = rhs.am1;
am2 = rhs.am2;
return *this;
}
语法是
MyStruct& operator=(const MyOtherStruct& rhs) {
// assignment logic goes here
return *this;
}
对于直接在MyStruct
体内的操作员.另请注意,我添加了惯用return *this
,让赋值返回对此对象的引用。
以响应OP编辑问题。您还可以在正文中声明运算符,并在其他地方定义它。在本例中,语法为:
MyClass::MyStruct& MyClass::MyStruct::operator=(const MyOtherStruct& rhs) {
// assignment logic goes here
return *this;
}
相关文章:
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 一种有效的数据结构,用于按 ID 访问和查找加权随机项
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- 基于浅树的数据结构的内存分配器,用于频繁分配和解除分配
- 如何知道用于实现标准代码段的确切数据结构和算法,例如在C++STL中?
- 用于对项目进行分组并将单个项目映射到其他组成员的数据结构
- 用于本地网络运行的客户端服务器体系结构
- 用于循环访问多个集合的数据结构
- C++中用于结构的纯数组的类似于TableView/DataFrame的通用功能
- 用于筛子的最佳数据结构是什么(即一些被划掉的数字列表)?
- 用于存储分组关系和支持外观的最佳数据结构
- 用于添加和查找查询的适当数据结构
- 用于向公众公开数据成员的帮助程序结构
- 用于基于节点的树结构的Python绑定
- Boost.Spirit.Qi 语法,用于 Boost.Fusion 自适应结构中的默认值
- 自定义分配器上的额外移动结构用于叮当声
- 现代C和C :可以将一个定义的结构用于其他声明的结构
- 如何序列化一个8位整数的结构用于套接字编程
- Cpp变量/结构用于存储128位数据