实现从一个类到另一个类的类型转换
Implement type casting from one class to another
假设我有两个不通过继承相关的类。 例如:
class MyString
{
private:
std::string str;
};
class MyInt
{
private:
int num;
};
我希望能够使用常规铸造将一个转换为另一个,例如 MyInt a = (MyInt)mystring
(其中mystring
是class MyString
)。
一个人如何完成这样的事情?
转换首先需要有意义。假设它确实如此,您可以实现自己的转换运算符,如下例所示:
#include <string>
#include <iostream>
class MyInt; // forward declaration
class MyString
{
std::string str;
public:
MyString(const std::string& s): str(s){}
/*explicit*/ operator MyInt () const; // conversion operator
friend std::ostream& operator<<(std::ostream& os, const MyString& rhs)
{
return os << rhs.str;
}
};
class MyInt
{
int num;
public:
MyInt(int n): num(n){}
/*explicit*/ operator MyString() const{return std::to_string(num);} // conversion operator
friend std::ostream& operator<<(std::ostream& os, const MyInt& rhs)
{
return os << rhs.num;
}
};
// need the definition after MyInt is a complete type
MyString::operator MyInt () const{return std::stoi(str);} // need C++11 for std::stoi
int main()
{
MyString s{"123"};
MyInt i{42};
MyInt i1 = s; // conversion MyString->MyInt
MyString s1 = i; // conversion MyInt->MyString
std::cout << i1 << std::endl;
std::cout << s1 << std::endl;
}
住在科里鲁
如果将转换运算符标记为 explicit
,这是可取的(需要 C++11 或更高版本),那么您需要显式强制转换,否则编译器会吐出错误,例如
MyString s1 = static_cast<MyString>(i1); // explicit cast
相关文章:
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- C++将一个指针分配给另一个指针时执行的类型检查
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- 另一个:从"常量类型*"到"类型*"的转换无效
- 将 std::variant 转换为另一个具有类型子集的 std::variant
- 我可以使用预处理器将一个类型声明替换为另一个类型声明吗?
- 将 std::variant 转换为另一个具有超类型集的 std::variant
- 在函数模板中将一个类型名映射到另一个类型名
- 如何将数组的整数与另一个类型为"int"的变量进行比较?
- 实现从一个类到另一个类的类型转换
- 如何检测一个类型是否是另一个类型的可见基
- 如何编写类型特征来检查一个类型是否可以通过非窄化转换转换为另一个类型
- 从成员函数指针到另一个类型的强制转换,返回严格的别名问题
- 如何将模板化类型的常量应用到另一个类型
- 在可强制转换为另一个模板类型的类模板中重载赋值操作符
- 类型转换到另一个具有名称空间的类
- 从一个类类型到另一类类型的数据转换
- 存储类型并以编程方式将另一个变量强制转换为存储的类型