今天学习了 重载运算符,
有一个重载[]的疑问
class A
{
public:
A(int n)
{
m_num = n;
}
int& getNum()
{
return m_num;
}
private:
int m_num;
};
int &operator
{
cout << "index:" << index << endl;
return a.getNum();
}
为什么重载运算符[]函数无法写成全局的 但++ -- 或者其他运算符都可以写在全局呢
https://wuyuans.com/2012/09/cpp-operator-overload/
以下一些双目运算符不能重载为类的友元函数:=、()、[]、->。
都可以写在全局的,只是要写在全局就要先负值再在类中引用。
一般来说,单目运算符我们提倡定义为成员函数。[]和=是一个道理:即编译器发现当类中没有定义这些运算符的重载成员函数时,就会自己加入默认的运算符重载成员函数,容易造成错误。
//VPoint.h文件
#pragma once
class VPoint
{
public:
VPoint(void);
VPoint(int x,int y,int z);
//运算符重载
//重载 + -
friend VPoint operator + (const VPoint& pt1, const VPoint& pt2);
friend VPoint oper......<br/><strong>答案就在这里:</strong><a target='_blank' rel='nofollow' href='http://blog.csdn.net/misakahina/article/details/39056309'>C++中的运算符重载问题</a><br/>----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。