简体   繁体   English

在 C++ 中重载不同类型

[英]Overloading different types in C++

Suppose we have the following class:假设我们有以下类:

class Rational { // Represents rational number. n=1/2=d for example.
public:
  int n = 0;
  int d = 1;
};

Rational x = Rational();
x.n = 1;
x.d = 2;

Is it possible to do overloading such that 3 * x would give 3/2 instead of an error?是否可以进行重载以使3 * x给出3/2而不是错误?

My teacher said that overloading happens only between objects of the same type, but why can we do overloading between cout which is of type ostream and an object of type Rational and not of the type int and Rational ?我的老师说重载只发生在相同类型的对象之间,但是为什么我们可以在ostream类型的coutRational类型的对象而不是intRational类型的对象之间进行重载?

You may write for example你可以写例如

Rational operator *( const Rational &r, int x )
{
    return { r.n * x, r.d };
}

Rational operator *( int x, const Rational &r )
{
    return { r.n * x, r.d };
}

You may overload operators for user defined types.您可以重载用户定义类型的运算符。 For a binary operator at least one of operands must be of a user defined type.对于二元运算符,至少一个操作数必须是用户定义的类型。

From the C++ 20 Standard (12.4.2.3 Operators in expressions)来自 C++ 20 标准(12.4.2.3 表达式中的运算符)

2 If either operand has a type that is a class or an enumeration, a user-defined operator function can be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. 2如果任一操作数的类型是类或枚举,则可以声明实现此运算符的用户定义的运算符函数,或者可能需要用户定义的转换将操作数转换为适合构建的类型-in 运算符。 In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator.在这种情况下,重载决策用于确定要调用哪个运算符函数或内置运算符来实现运算符。 Therefore, the operator notation is first transformed to the equivalent function-call notation as summarized in Table 15 (where @ denotes one of the operators covered in the specified subclause).因此,运算符符号首先转换为表 15 中总结的等效函数调用符号(其中 @ 表示指定子条款中涵盖的运算符之一)。 However, the operands are sequenced in the order prescribed for the built-in operator (7.6).但是,操作数按照为内置运算符 (7.6) 规定的顺序进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM