结构体的强制装换

1.定义结构体

struct newtype
{
long long n;
int other,things;
}

2.在结构体定义中插入如此一段代码

operator long long()
{
    return n;
}

如此一来,就可以像这样使用了:

newtype ne;
ne.n=65536;
int x=ne;

但是,写这样一段代码却会报错,应该怎么办呢?难道要去改头文件写int的强制转换吗?

int x=65536;
newtype ne=x;

经过实验发现,其实重载一次运算符“=”就可以了。代码如下(放在结构体定义中)

newtype &operator=(long long val)
{
    n=val;
}

现在这样就是正确的了:

long long x;
x=(newtype)12345;

其实有的时候定义强制装换比重载运算符要方便得多。比如像现在这样,就不用再定义减号、乘号和除号了。

转载于:https://www.cnblogs.com/Bear-Dictionary/p/3551687.html

猜你喜欢

转载自blog.csdn.net/weixin_33907511/article/details/93353998
今日推荐