gpt4 book ai didi

c++ - 为什么作为类成员的重载运算符只能有一个参数

转载 作者:太空狗 更新时间:2023-10-29 23:31:26 25 4
gpt4 key购买 nike

为什么我不能像这样使用带有 2 个参数的重载运算符作为类的成员:

myclass& operator+(const otherclass& cl, int value);

最佳答案

类函数有一个隐式的 this 参数,因此在类中声明的双参数运算符会隐式地希望采用比实际可能更多的参数:a + b其中 a 是类 C 的实例,是 a.operator+(b) 的糖,而不是 C::operator+(a, b)。如果只是想让运算符的声明与类体保持一致,可以将它们声明为friend 函数:

class C {
public:
friend C& operator+(const C& a, const C& b);
};

关于c++ - 为什么作为类成员的重载运算符只能有一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4808178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com