关于C++中赋值运算符的问题
请原谅对某些人来说似乎是一个非常简单的问题,但我想到了这个用例:
struct fraction {
fraction( size_t num, size_t denom ) :
numerator( num ), denominator( denom )
{};
size_t numerator;
size_t denominator;
};
我想做的是使用如下语句:
fraction f(3,5);
...
double v = f;
让 v
现在保存由 my 表示的值分数。 我将如何在 C++ 中做到这一点?
Forgive what might seem to some to be a very simple question, but I have this use case in mind:
struct fraction {
fraction( size_t num, size_t denom ) :
numerator( num ), denominator( denom )
{};
size_t numerator;
size_t denominator;
};
What I would like to do is use statements like:
fraction f(3,5);
...
double v = f;
to have v
now hold the value represented by my fraction.
How would I do this in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
实现此目的的一种方法是定义一个转换运算符:
大多数人出于风格原因不愿意定义隐式转换运算符。 这是因为转换运算符往往在“幕后”运行,并且很难判断正在使用哪些转换。
在此版本中,您将调用
as_float
方法来获得相同的结果。One way to do this is to define a conversion operator:
Most people will prefer not to define an implicit conversion operator as a matter of style. This is because conversion operators tend to act "behind the scenes" and it can be difficult to tell which conversions are being used.
In this version, you would call the
as_float
method to get the same result.赋值运算符和转换构造函数用于从其他类的对象初始化您的类的对象。 相反,您需要一种方法来使用您的类的对象初始化其他类型的对象。 这就是转换运算符的用途:
Assignment operators and conversion constructors are for initializing objects of your class from objects of other classes. You instead need a way to initialize an object of some other type with an object of your class. That's what a conversion operator is for:
您可以使用运算符 double 进行转换:
You can use the operator double to convert:
operator=
与它无关,而是您想向您的struct
添加一个公共operator double
,如下所示:operator=
has nothing to do with it, rather you want to add to yourstruct
a publicoperator double
something like:有了这么多代码,这将是编译器错误,因为编译器不知道如何将结构分数转换为双精度。 如果您想提供转换,那么您必须定义编译器将使用的
operator double()
来进行此转换。With that much of code it will be compiler error as the compiler doesn't how to convert struct fraction into a double. If you want to provide the conversion then you have to define the
operator double()
which will be used by the compiler for this conversion.