什么是“operator int”?功能?
下面的“operator int”函数是什么?它有什么作用?
class INT
{
int a;
public:
INT(int ix = 0)
{
a = ix;
}
/* Starting here: */
operator int()
{
return a;
}
/* End */
INT operator ++(int)
{
return a++;
}
};
What is the "operator int" function below? What does it do?
class INT
{
int a;
public:
INT(int ix = 0)
{
a = ix;
}
/* Starting here: */
operator int()
{
return a;
}
/* End */
INT operator ++(int)
{
return a++;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
粗体代码是转换运算符。 (又名强制转换运算符 )
它为您提供了一种从自定义
INT
类型转换为另一种类型(在本例中为int
)的方法,而无需显式调用特殊的转换函数。例如,使用转换运算符,此代码将编译:
如果没有转换运算符,上述代码将无法编译,并且您必须执行其他操作才能从
INT
转换为int
,如:The bolded code is a conversion operator. (AKA cast operator)
It gives you a way to convert from your custom
INT
type to another type (in this case,int
) without having to call a special conversion function explicitly.For example, with the convert operator, this code will compile:
Without the convert operator, the above code won't compile, and you would have to do something else to go from an
INT
to anint
, such as:operator int()
是一个转换运算符,它允许使用此类来代替int
。如果在需要int
(或其他数字类型)的地方使用此类型的对象,则此代码将用于获取正确类型的值。例如:
operator int()
is a conversion operator, which allows this class to be used in place of anint
. If an object of this type is used in a place where anint
(or other numerical type) is expected, then this code will be used to get a value of the correct type.For example:
首先要做的事情是:
在您的示例中,INT 是一个用户定义的类,具有来自“int”的转换构造函数。
因此,以下代码格式良好:
这意味着您可以从整数获取 INT 对象。但是如果必须将 INT 对象转换回整数,该怎么办?
可以说 INT 类可以提供一个成员函数来返回封装的整数成员,
但这不是很直观,也不是一种标准化方法。此外,当谈到内置类型在这种情况下如何工作时,它是不直观的,
因此标准允许通过以下方式转换用户定义类型的标准化和直观性:
这使得以下所有内容都格式良好,并且与内置类型的工作方式保持和谐
First things first:
In your example, INT is a User Defined class that has a converting constructor from 'int'.
Therefore the following code is well-formed:
This means that you can get an INT object from an integer. However what does one do, if the INT object has to be converted back to an integer? Transitivity?
One can say that the class INT can provide a member function to return the encapsulated integer member
This however is not very intuitive and is not a standardized approach. Also it is not intuitive when it comes to how built-in types work in such situations.
Therefor the Standard allows for such standardization and intuitiveness of converting User Defined Types by saying:
This makes all of the following well-formed and retains harmony with the way built-in types work is
看起来它创建了一个 INT 类,其行为有点像常规 int,只是尚未定义一些其他运算符。
这是家庭作业的问题吗?
It looks like it make an INT class which behaves a little like the regular int, just that some other operators are not yet defined.
Is this a homework problem?
看起来这是一个课堂问题,所以我会邀请您查看有关如何创建课程的文档。
Seems like it's a question from a classroom, so I'll invite you to check the documentation on how to create a class.