为两个类定义重载的强制转换运算符,这两个类之间具有循环依赖关系
Define overloaded casting operator for two classes with circular dependency between them
我有两个类String
和Integer
我希望String
能够被转换为Integer
并且Integer
能够被转换成String
我使用运算符重载实现它的方式如下(注意Integer
类是基于模板的)
#include <string>
class Integer; // forward declaration but doesnt fix the compiler error
class String {
public:
operator Integer() {
try {
return std::stoi(s);
catch(std::invalid_argument ex) {
}
}
std::wstring s;
};
template<class T>
class intTypeImpl {
T value;
public:
typedef T value_type;
intTypeImpl() :value() {}
intTypeImpl(T v) :value(v) {}
operator T() const {return value;}
operator String() {
return std::to_wstring(value);
}
};
typedef intTypeImpl<int> Integer;
编译器正在发布
错误C2027:使用未定义的类型"Integer"
因此正向声明没有任何用处
我应该如何实现这一点?
如有任何帮助,我们将不胜感激。
在类外重载铸造运算符:
/* after every line of code you posted */
operator Integer(const String& str){
return std::stoi(str.s);
}
intTypeImpl
中的铸件:
#include <type_traits>
/* in intTypeImpl */
intTypeImpl()=default;
intTypeImpl(const intTypeImpl<T>&)=default;
intTypeTmlp(String& str){
static_assert(
std::is_same<T, int>,
"String can be converted only to intTypeImpl<int>"
);
value=std::stoi(str.s);
}
相关文章:
- 给定两个偶数,求出它们之间所有偶数的平方和
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 如何在两个 boost::multi_arrays (C++) 之间执行数学运算?
- 查找字符在两个索引之间出现的次数
- 如何使用 OpenCV 解码在两个 UWP 应用之间发送的图像字节?
- C++两个源文件之间共享的枚举的静态实例
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 以天C++为单位的两个时间戳之间的差异
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 通过插槽和信号在不同线程中的两个qt对象之间进行通信
- 在C++中查找两个向量之间最相似的值
- 两个有符号数字之间的距离
- Directx 12 :在两个进程之间共享图形内存
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 是否有一种标准方法来计算两个 asctime() 值之间的天数
- 如何找到两个棋盘平面之间的角度?
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 将两个数字替换为给定数组中介于两个之间的单个数字
- 如何在两个其他两个之间设置工具栏