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

时间:2016-02-03 16:09:04

标签: c++ oop

假设我有两个与继承无关的类。 e.g:

as Java Application

我希望能够使用常规投放将其中一个转换为另一个,例如class MyString { private: std::string str; }; class MyInt { private: int num; }; (其中MyInt a = (MyInt)mystringmystring)。

如何完成这样的事情?

1 个答案:

答案 0 :(得分:5)

转换首先需要有意义。假设确实如此,您可以实现自己的转换运算符,如下例所示:

#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;
}

Live on Coliru

如果您将转换运算符标记为explicit,这是更可取的(需要C ++ 11或更高版本),那么您需要显式转换,否则编译器会发出错误,例如

MyString s1 = static_cast<MyString>(i1); // explicit cast