Konwersja między klasami

0

Witam,
jak zrobić konwersję między klasami Vector2D i Vector3D?

Zrobiłem konwersję z klasy Vector3D na klasę Vector2D funkcją konwertującą.
Polecenie do zadania brzmiało: "Do klasy Vector2D dodać konwersję do klasy Vector3D" - zrobiłem konwersję konstruktorem, ale nie jest to do końca poprawne rozwiązanie...

Mój kod wygląda następująco:

#include <iostream>
using namespace std;

class Vector2D {
public:
    Vector2D(float x, float y) : x(x), y(y) { }

    void print() { cout << "(" << x << ", " << y << ")" << endl; }

    float getX() { return x; }
    float getY() { return y; }

private:
    float x;
    float y;
};


class Vector3D {
public:
    Vector3D(float x, float y, float z) : x(x), y(y), z(z) { }

    void print() { cout << "(" << x << ", " << y << ", " << z << ")" << std::endl; }

    operator Vector2D() {
        return Vector2D(x,y);
    }

    Vector3D(Vector2D other)
        : x(other.getX()),
          y(other.getY()),
          z(0.0)
    { }

    float getX() { return x; }
    float getY() { return y; }
    float getZ() { return z; }

private:
    float x;
    float y;
    float z;
};


int main() {
    return 0;
}

 
0

cast operator

0

Przecież we własnym kodzie masz coś takiego:

operator Vector2D() {
    return Vector2D(x,y);
}

No to coś podobnego jest potrzebne teraz w Vector2D.

0
    operator Vector3D() {
        return Vector3D(x,y,0.0);
    }

Próbowałem coś takiego dopisać, ale dopisanie czegoś takiego w klasie Vector2D generuje nam błąd "C1001: An internal error has occurred in the compiler."
Kompilator MSVC.

1

Najpierw potrzebna jest deklaracja Vector3D przed Vector2D (forward declaration), a sama definicja funkcji musi być po definicji Vector3D:
http://ideone.com/lyDmss

0

dzięki :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1