static_cast与直接调用转换运算符? [英] static_cast vs. direct call to conversion operator?

查看:134
本文介绍了static_cast与直接调用转换运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下类,作为一个简单示例:

Consider the following class, just as a simple example:

#include <iostream>
#include <string>
using namespace std;

class point {
public:
    int _x{ 0 };
    int _y{ 0 };

    point() {}
    point(int x, int y) : _x{ x }, _y{ y } {}
    operator string() const
        { return '[' + to_string(_x) + ',' + to_string(_y) + ']'; }

    friend ostream& operator<<(ostream& os, const point& p) {

        // Which one? Why?
        os << static_cast<string>(p); // Option 1
        os << p.operator string();    // Option 2

        return os;
    }
};

应该直接致电转换操作员,还是直接致电 static_cast

Should one call a conversion operator directly, or rather just call static_cast and let that do the job?

那两行几乎可以做完全相同的事情(这就是所谓的转换运算符),没有据我所知,他们的行为之间存在真正的差异。所以这里真正的问题是这是否正确。即使这些对我来说似乎是相同的,但仍然可能会有细微的差异,人们可能无法理解。

Those two lines will pretty much do exactly the same thing (which is to call the conversion operator), there's no real difference between their behavior as far as I can tell. So the real question here is whether that's true or not. Even though these seem the same to me, there could still be subtle differences that one might fail to pick up on.

因此,这些方法之间是否存在任何实际差异(包括可能不适用于此示例),除了它们的语法不同之外?

So are there any practical differences between those approaches (including ones that might not apply to this example), other than the fact that the syntax for them different? Which one should be preferred and why?

推荐答案


那么这些方法之间是否有实际区别? / p>

So are there any practical differences between those approaches

在这种情况下,我不知道这是明智的行为。

In this case, not that I know of, behaviour wise.


(包括可能不适用于本示例的内容)

(including ones that might not apply to this example)

static_cast< X> ;(instance_of_Y)如果 X 具有类型为 Y 。显式调用 Y (可能不存在)转换运算符不能使用上述转换构造函数。当然,在这种情况下, std :: string 没有用于 point 的转换构造函数。

static_cast<X>(instance_of_Y) would also allow conversion if X has a converting constructor for the type Y. An explicit call to (possibly non-existent) conversion operator of Y could not use the mentioned converting constructor. In this case of course, std::string does not have a converting constructor for point.

因此,演员阵容更加通用,这就是我通常所希望的。同样,将这个对象转换为 string 调用操作符 string()<更有意义。 / code> 。但是,如果出于某些非常奇怪的原因而要避免使用转换构造函数,则对转换运算符的显式调用将实现这一点。

So, the cast is more generic and that is what I would prefer in general. Also "convert this object to type string" is more meaningful than "call the operator string()". But if for some very strange reason you want to avoid the converting constructor, then explicit call to conversion operator would achieve that.

这篇关于static_cast与直接调用转换运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆