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

标签 c++ oop

假设我有两个没有继承关系的类。例如:

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

Live on Coliru

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

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

关于c++ - 实现从一个类到另一个类的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35181987/

相关文章:

c++ - 在使用 Rcpp 时从 C++ 调用 GLPK

ruby - 没有类方法获取 Ruby 类名

oop - 我将如何控制这个文本游戏以及类如何获得更好的结构来做到这一点?

c# - 从基类创建派生类的实例

c++ - 在使用 C++ 的虚拟继承期间调用构造函数

c++ - 嵌套类中的 "Invalid covariant return type"错误,其方法返回基于模板的对象

android - 在 Android 上为共享库导出类时出现问题

c++ - #if 0 后面到底可以放什么?

java - 这两副牌设计模式中哪一种更稳定/更受欢迎?

c++ - 工厂应该负责重建序列化对象吗?