C++ 中的运算符重载
所以我正在参加基础编程 II 课程。我们必须创建一个程序来实现 4 个不同的功能,从而改变操作员的工作方式。我已经查找了多个示例和多组文本来显示如何执行此操作,但我无法确定任何代码的含义。对我来说这样的事情应该有效。
int operator++()
{
variableA--;
}
对我来说,这表示如果您遇到 ++,那么 - 从变量来看,现在显然它不会像这样工作。我发现的所有示例都创建了自己的数据类型。有没有办法使用 int
或 double
重载运算符?
So I'm in a basic programming II class. We have to create a program that makes 4 different functions that will change the way an operator works. I've looked up multiple examples and sets of text that display how to do this, but I cannot make which way of what any of the code means. To me something like this should work.
int operator++()
{
variableA--;
}
To me, this says if you encounter a ++, then -- from the variable, now obvious it doesn't work like this. All the examples I've found create their own data type. Is there a way to overload an operator using an int
or a double
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所有示例都创建自己的数据类型,因为这是运算符重载的规则之一: 重载运算符必须至少适用于一种用户定义类型。
即使您可以为整数重载
++
,编译器也不知道要使用哪一个——您的版本还是常规版本;这会是模棱两可的。您似乎将运算符视为单个函数,但每个重载都是一个完全独立的函数,通过其函数签名(类型,有时是参数数量)来区分,同时具有相同的运算符符号(这是“重载”的定义)。
因此,您不能重载
++
来总是做不同的事情;这实际上是运算符重写,C++ 不允许这样做。您可以为您创建的类型定义
++
:请注意,这组
++
运算符是在 MyType 类外部定义的,但也可以在内部定义相反(他们可以通过这种方式访问非公共成员),尽管他们的实现会略有不同。All the examples create their own data type since this is one of the rules for operator overloading: An overloaded operator must work on at least one user-defined type.
Even if you could overload
++
for integers, the compiler wouldn't know which one to use -- your version or the regular version; it would be ambiguous.You seem to think of operators as single functions, but each overload is a completely separate function differentiated by its function signature (type and sometimes number of arguments), while having the same operator symbol (this is the definition of "overloading").
So, you can't overload
++
to always do something different; this would really be operator overriding, which C++ doesn't allow.You can define
++
for a type you've created though:Note that this set of
++
operators was defined outside of the MyType class, but could have been defined inside instead (they would gain access to non-public members that way), though their implementations would be a little different.您不能重载内置类型的运算符。 (好吧,从技术上讲,你可以重载“int + MyClass”之类的东西 - 但当两边都是内置类型时就不行了)
You can't overload operators of built-in types. (Well, technically you can overload things like "int + MyClass" - but not when both sides are built-in types)
看看 如何重载前缀和后缀形式运算符 ++ 和 --?
Take a look at How can I overload the prefix and postfix forms of operators ++ and --?