Do not tell me how to convert one class to another? For example, I have classes:

class A { public: int *a; } 

and

 class S { public: std::string *s; } 

and I created 2 objects:

 A tmp1; S tmp2; tmp1 = (mp_it1)tmp2; tmp1 != tmp2; 

I guess I need something like operator А() const { } in class S and the like in class А But how can I also pass class variables I can't imagine?

How do I implement this peretypovyvanie? Very desirable with an example.

    2 answers 2

    In the general case, the conversion of any class A to another class B can be implemented in three ways:

    1. In class B add a constructor that takes an argument of type A or any other type to which A can be converted implicitly:

       struct B { B(const A& a) {/* формируем новый объект типа B из переменной `a` */} }; 
    2. In class A add a conversion operator to B :

       struct A { operator B() const {/* формируем новый объект типа B из this и возвращаем */} }; 
    3. Implement the transformation function, i.e. any function that takes A (or any other type into which A can be implicitly converted) and returns B :

       B f(const A& a) {/* формируем новый объект типа B из переменной `a` и возвращаем */} 

    Which option to choose depends on the situation:

    • If class B allows modification, then the first option should be chosen as the most obvious from the point of view of the language (the constructor is responsible for creating the object).
    • If class B does not allow modification (or is not a class at all, for example, it can be just an int ), and class A allows, then use the second option.
    • If neither A nor B can be changed, then use the third option.

    The first two options can be used for implicit type conversion (unless the explicit keyword is specified). The third option would require explicitly calling the conversion function.

      The solution was easier than I thought:

       operator А() const { return А(); } 

      In both classes, there must be constructors that “know” how to work with variables of other classes.

      For example in A:

       A::A(std::string s) { //тут преобразуем в int }