我有两个类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;
编译器正在发出
error C2027: use of undefined type 'Integer'
所以前向声明没有用。
我应该如何实现这个?
任何帮助将不胜感激。
最佳答案
在类外部重载的强制转换运算符:
/* after every line of code you posted */
operator Integer(const String& str){
return std::stoi(str.s);
}
在 intTypeImpl
中类型转换 c-tor:
#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++ - 为两个类之间具有循环依赖关系定义重载转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564718/