实现从一个类到另一个类的类型转换

Implement type casting from one class to another

本文关键字:另一个 类型转换 一个 实现      更新时间:2023-10-16

假设我有两个不通过继承相关的类。 例如:

class MyString
{
    private:
        std::string str;
};
class MyInt
{
    private:
        int num;
};

我希望能够使用常规铸造将一个转换为另一个,例如 MyInt a = (MyInt)mystring(其中mystringclass 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
相关文章: