[C++]C++重载 opeartor= must be a nonstatic member function?
来源:互联网 发布:java深度优先遍历 编辑:程序博客网 时间:2024/05/04 16:16
code
#include <iostream>using namespace std;class C {public: int x; C () {} C(int a) : x(a) {} // member function C operator = (const C&);};C C::operator= (const C& param) { x = param.x; return *this;}int main(){ C foo(1); cout <<"foo.x = " << foo.x << endl; C bar; bar = foo; cout <<"bar.x = " << bar.x << endl; return 0;}
run
foo.x = 1bar.x = 1
ERROR
opeartor= must be a nonstatic member function
note
引用
Notice that some operators may be overloaded in two forms: either as a member function or as a non-member function
许多运算符可以作为 member function 以及 non-member function 两种形式被重载
说明
- 所谓member function就是code部分所示的那样,在类的定义中有一个关于需要被重载的运算符的简单声明,比如:
C operator = (const C&);
这里重载了运算符=(等号);
- 与之相对的,non-member function 就是类定义里没有这种语句的,比如某个类的完整定义只有下面这些组成:
class D {public: int y; D () {} D (int b) : y(b) {}};
- C++中有许多运算符,比如=(等号),只能作为member function被重载,也就是说,必须在类的定义里声明一下,见code;
- 同时的,也有些运算符,比如+(加号),可以既作为 member function 又作为non-member function被重载。
疑惑
在我阅读的toturial[1]Classes (II)/The keyword this 部分的示例代码如下:
CVector& CVector::operator= (const CVector& param){ x=param.x; y=param.y; return *this;}
注意,这里写得是CVector&
,参照这个代码写的类C
,那么对于=(等号),就应该写成C&
,但是这样编译器(DEV C++ ISO C++11)会报ERROR,修改成最终code部分才能通过编译,这是目前自己的代码和示例代码不一致的地方。
reference
Classes (II)
http://www.cplusplus.com/doc/tutorial/templates/
1 0
- [C++]C++重载 opeartor= must be a nonstatic member function?
- 'operator =' must be a <Unknown> member
- Const Member Function(C++)
- error C2600: 'Point::Point' : cannot define a compiler-generated special member function (must be de
- Can a member function template be virtual?
- reference to non-static member function must be called
- Name of an object member must be a string
- C++, Define A Type Member
- c++学习-reference to non-static member function must be called
- Appium uncaughtException: fn must be a function 解决方法
- render() must be called with a dict, not a Context. return HttpResponse(t.render(c))解决
- Fatal error: Call to a member function fetch_row() on a non-object in C:\wamp\www\baicaotang\admin\m
- opeartor 关键字重载 实验
- C#Connection must be valid and open?
- must be in segment block c
- Bindable must be on a member in an Observable class.报错解决
- 【c++】cannot declare member function *** to have static linkage [-fpermissive]
- The function default must be used with a prefix when a default namespace is not specified
- Volley 源码分析(一)
- 16位汇编 call调用函数 通过栈来传递参数
- 2016年9月2号-心情很差--收发广播Broadcast,两个广播同时发出的接收与本项目发出广播,另一个项目接收广播
- Python2(Python基础)
- Data Stream as Disjoint Intervals
- [C++]C++重载 opeartor= must be a nonstatic member function?
- Linux 日志级别(loglevel)详解
- 动态连通性问题(2)
- Java笔记--Web知识汇总之一 HTML
- 100.Remove Duplicates from Sorted Array-删除排序数组中的重复数字(容易题)
- System.currentTimeMillis()与日期之间的相互转换
- [MongoDB]Update更新数据
- 总结:特权级之间的转换
- bzoj 2038 小Z的袜子(莫队)