gpt4 book ai didi

C++增量++运算符重载

转载 作者:行者123 更新时间:2023-11-28 00:14:14 27 4
gpt4 key购买 nike

如果我正在使用一个类,我知道如何重载运算符 +=

class temp
{
public:
int i;
temp(){ i = 10; }
int operator+=(int k)
{
return i+=k;
}
};
int main()
{
temp var;
var += 67;
cout << var.i;
return 0;
}

但为什么我不能为基本数据类型创建一个重载的 += 函数

int operator+=(int v, int h)
{
return v += (2*h);
}
int main()
{
int var = 10;
var += 67;
cout << i;
return 0;
}

编译上述重载函数时出现错误。

最佳答案

不允许为原始类型重载运算符。作为引用,请参阅此处编写的内容:

http://www.cprogramming.com/tutorial/operator_overloading.html

但是,您可以通过围绕要重载的原始类型创建一个“包装器”类,然后创建一个“转换构造函数”以从原始类型转到您的自定义类和另一个“转换运算符”来产生类似的效果从您的包装器自定义类型返回原始类型。

对于你的临时类是这样的:

class temp
{
public:
int i;
temp(const int& orig){ i = orig; }
operator int(void) const { return i; }
int operator+=(int k)
{
return i+=k;
}
};

关于C++增量++运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31353578/

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