如何将C ++类/结构转换为原始/不同类型/类/结构?

编程入门 行业动态 更新时间:2024-10-23 11:30:20
本文介绍了如何将C ++类/结构转换为原始/不同类型/类/结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下类CppProperty类保存值:

I have the following class CppProperty class that holds value:

template<typename TT> class CppProperty { TT val; public: CppProperty(void) { } CppProperty(TT aval) : val(aval) { } CppProperty(const CppProperty & rhs) { this->val = rhs.val; } virtual ~CppProperty(void) { } TT operator=(TT aval) { this->val = aval; return this->val; } friend TT operator++(CppProperty & rhs); friend TT operator--(CppProperty & rhs); friend TT operator++(CppProperty & rhs, int); friend TT operator--(CppProperty & rhs, int); //template<typename RR> //friend RR operator=(RR & lhs, const CppProperty & rhs); //friend int & operator=(int & lhs, const CppProperty & rhs); //int reinterpret_cast<int>(const CppProperty & rhs); };

我想这样做:

CppProperty<char> myproperty(10); myproperty++; int count = myproperty;

如何做到这一点?我不能覆盖operator =。任何帮助,非常感谢!谢谢!

How this can be done? I can't override the operator=. Any help is greatly appreciated! Thank you!

推荐答案

您需要一个转换运算子:

You'd need a conversion operator:

operator const TT&(void) const { return val; } operator TT&(void) { return val; }

有一个关于转换运算符的简短教程此处。简而言之,当编译器尝试转换类型时,它将首先查看右侧的一个操作符,它将它转换为所需的类型。我们所做的是说 TT 是,这个类可以转换为它。

There is a brief tutorial on conversion operators here. In short, when the compiler tries to convert a type, it will first look at the right-hand side for an operator that will convert it to the desired type. What we are doing is saying "Whatever TT is, this class can be converted to it".

运算符,它看起来看是否左侧可以从右侧构建,等等。 (直到,如果找不到转换,则会发生错误。)

If no operators are found, it looks to see if the left-hand side can be constructed from the right-hand side, and so on. (Until, if it cannot find a conversion, it emits an error.)

可以删除你明确定义的默认构造函数,如果你像这样声明你的其他构造函数:

You can remove your explicitly defined default constructor if you declare your other constructor like this:

// If not specified, construct with default-constructed type. CppProperty(TT aval = TT()) : val(aval) { }

更多推荐

如何将C ++类/结构转换为原始/不同类型/类/结构?

本文发布于:2023-11-06 06:53:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562991.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构   转换为   不同类型   如何将   原始

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!