[C++]C++重载 opeartor= must be a nonstatic member function?

本文详细介绍了C++中的运算符重载机制,特别是针对赋值运算符=的重载实现进行了深入探讨。文中通过具体示例对比了成员函数与非成员函数重载的区别,并解释了某些运算符为何只能作为成员函数进行重载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 = 1
bar.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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值