加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – static_cast与直接调用转换运算符?

发布时间:2020-12-16 10:03:07 所属栏目:百科 来源:网络整理
导读:考虑以下类,就像一个简单的例子: #include iostream#include stringusing 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) + ',
考虑以下类,就像一个简单的例子:

#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并让它完成工作?

这两行几乎完全相同(就是调用转换运算符),就我所知,它们的行为没有真正的区别.所以这里真正的问题是这是否真实.虽然这对我来说似乎是一样的,但仍然可能存在一些人们可能无法接受的微妙差异.

那些方法之间是否有任何实际差异(包括可能不适用于此示例的方法),除了它们的语法不同的事实?应该首选哪一个?为什么?

解决方法

So are there any practical differences between those approaches

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

(including ones that might not apply to this example)

如果X具有类型Y的转换构造函数,则static_cast< X>(instance_of_Y)也允许转换.对Y的(可能不存在的)转换运算符的显式调用不能使用所提到的转换构造函数.当然,在这种情况下,std :: string没有用于point的转换构造函数.

因此,演员表更通用,这是我一般喜欢的. “将此对象转换为类型字符串”也比“调用运算符字符串()”更有意义.但是如果出于一些非常奇怪的原因你想避免使用转换构造函数,那么显式调用转换运算符就可以实现这一点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读