假设我有两个与继承无关的类.例如:
class MyString
{
private:
std::string str;
};
class MyInt
{
private:
int num;
};
Run Code Online (Sandbox Code Playgroud)
我希望能够以一个转换到另一种使用常规铸造如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;
}
Run Code Online (Sandbox Code Playgroud)
如果你将转换运算符标记为explicit,这是更可取的(需要C++ 11或更高版本),那么你需要显式转换,否则编译器会发出错误,比如
MyString s1 = static_cast<MyString>(i1); // explicit cast
Run Code Online (Sandbox Code Playgroud)