-1

Собственно задание:

Нужно написать класс описывающий обычный вектор на плоскости. Для этого класса вам нужно реализовать сложение, вычитание, умножение на число (слева и справа) и сравнение на равенство/неравенство. Все операторы должны быть реализованы как внешние функции. Короткие версии операторов реализовывать не нужно.

Кроме того нужно реализовать конструктор от Vector2D с другим шаблонным параметром. Т.е. должен корректно работать следующий код:

Vector2D v(1,2); Vector2D w(v);

вроде все написал, но не могу корректно перегрузить операторы с использованием шаблонов. Расскажите, пожалуйста, как. Спасибо!

Естественно, например такой код не работает: Vector2D v(1,2); Vector2D res = v * 3;

но если нужно чтобы и он работал, то как перегрузить еще операторы не добавляю новых функций? Как закастовать переданный Vector2D в другой тип? (который требуется на выходе)

вот весь код класса:

#include <iostream>
#include <stdlib.h>

using namespace std;

// шаблонный класс Vector2D
template <class T>
struct Vector2D
{
     Vector2D() { x = 0; y = 0; }
     Vector2D(T x, T y) : x(x), y(y) {}

     template <class V> Vector2D(V const& v) {
        x = (T) v.x;
        y = (T) v.y;
     }
public:
     T x;
     T y;
};

// оператор +
template <class T>
Vector2D<T> operator + (Vector2D<T> & a, Vector2D<T> const& b) {
    a.x = a.x + b.x;
    a.y = a.y + b.y;
    return a;
}

// оператор -
template <class T>
Vector2D<T> operator - (Vector2D<T> & a, Vector2D<T> const& b) {
    a.x = a.x - b.x;
    a.y = a.y - b.y;
    return a;
}

// оператор умножения на число слева
template <class T>
Vector2D<T> operator * (T k, Vector2D<T> & a) {
    a.x = a.x * k;
    a.y = a.y * k;
    return a;
}

// оператор умножения на число справа
template <class T>
Vector2D<T> operator * (Vector2D<T> & a, T k) {
    a.x = a.x * k;
    a.y = a.y * k;
    return a;
}

Сервер же выдает такую ошибку:

Compilation error
main.cpp: In instantiation of ‘void check_operations(double, double, double, double) [with T = int]’:
main.cpp:151:56:   required from here
main.cpp:145:23: error: no matching function for call to ‘operator+(VTest2D&, Vector2D&)’
     operator+(ta, b);
                       ^
main.cpp:145:23: note: candidates are:
main.cpp:29:13: note: template Vector2D operator+(Vector2D&, const Vector2D&)
 Vector2D operator + (Vector2D & a, Vector2D const& b) {
             ^
main.cpp:29:13: note:   template argument deduction/substitution failed:
main.cpp:145:23: note:   cannot convert ‘ta’ (type ‘VTest2D’) to type ‘Vector2D&’
     operator+(ta, b);
                       ^
main.cpp:79:12: note: template VTest2D operator+(const VTest2D&, const VTest2D&)
 VTest2D operator+(VTest2D const& a, VTest2D const& b)
            ^
main.cpp:79:12: note:   template argument deduction/substitution failed:
main.cpp:145:23: note:   cannot convert ‘b’ (type ‘Vector2D’) to type ‘const VTest2D&’
     operator+(ta, b);
                       ^
main.cpp:146:23: error: no matching function for call to ‘operator-(VTest2D&, Vector2D&)’
     operator-(ta, b);
                       ^
main.cpp:146:23: note: candidates are:
main.cpp:37:13: note: template Vector2D operator-(Vector2D&, const Vector2D&)
 Vector2D operator - (Vector2D & a, Vector2D const& b) {
             ^
main.cpp:37:13: note:   template argument deduction/substitution failed:
main.cpp:146:23: note:   cannot convert ‘ta’ (type ‘VTest2D’) to type ‘Vector2D&’
     operator-(ta, b);
                       ^
main.cpp:85:12: note: template VTest2D operator-(const VTest2D&, const VTest2D&)
 VTest2D operator-(VTest2D const& a, VTest2D const& b)
            ^
main.cpp:85:12: note:   template argument deduction/substitution failed:
main.cpp:146:23: note:   cannot convert ‘b’ (type ‘Vector2D’) to type ‘const VTest2D&’
     operator-(ta, b);
                       ^
main.cpp: In instantiation of ‘void check_operations(double, double, double, double) [with T = double]’:
main.cpp:152:56:   required from here
main.cpp:145:23: error: no matching function for call to ‘operator+(VTest2D&, Vector2D&)’
     operator+(ta, b);
                       ^
main.cpp:145:23: note: candidates are:
main.cpp:29:13: note: template Vector2D operator+(Vector2D&, const Vector2D&)
 Vector2D operator + (Vector2D & a, Vector2D const& b) {
             ^
main.cpp:29:13: note:   template argument deduction/substitution failed:
main.cpp:145:23: note:   cannot convert ‘ta’ (type ‘VTest2D’) to type ‘Vector2D&’
     operator+(ta, b);
                       ^
main.cpp:79:12: note: template VTest2D operator+(const VTest2D&, const VTest2D&)
 VTest2D operator+(VTest2D const& a, VTest2D const& b)
            ^
main.cpp:79:12: note:   template argument deduction/substitution failed:
main.cpp:145:23: note:   cannot convert ‘b’ (type ‘Vector2D’) to type ‘const VTest2D&’
     operator+(ta, b);
                       ^
main.cpp:146:23: error: no matching function for call to ‘operator-(VTest2D&, Vector2D&)’
     operator-(ta, b);
                       ^
main.cpp:146:23: note: candidates are:
main.cpp:37:13: note: template Vector2D operator-(Vector2D&, const Vector2D&)
 Vector2D operator - (Vector2D & a, Vector2D const& b) {
             ^
main.cpp:37:13: note:   template argument deduction/substitution failed:
main.cpp:146:23: note:   cannot convert ‘ta’ (type ‘VTest2D’) to type ‘Vector2D&’
     operator-(ta, b);
                       ^
main.cpp:85:12: note: template VTest2D operator-(const VTest2D&, const VTest2D&)
 VTest2D operator-(VTest2D const& a, VTest2D const& b)
            ^
main.cpp:85:12: note:   template argument deduction/substitution failed:
main.cpp:146:23: note:   cannot convert ‘b’ (type ‘Vector2D’) to type ‘const VTest2D&’
     operator-(ta, b);
                       ^

1 ответ 1

0

Формулировка интересная. Что характерно у меня в VS2013 все компилируется нормально. Только код

Vector2D<double> v(1, 2); 
Vector2D<double> res = v * 3.0;

Для умножения лучше использовать

template <class T, class N> Vector2D<T> operator * (Vector2D<T> & a, N k)
23
  • Как у вас может компилироваться?! Вы, вообще-то, смотрели сообщения об ошибках в вопросе? Что у вас, например, VTest2D? 8 ноя 2015 в 12:28
  • int _tmain(int argc, _TCHAR* argv[]) { Vector2D<double> a, b; a = a + b; Vector2D<double> v(1, 2); Vector2D<double> res = v * 3.0; return 0; } Что такое VTest2D я и сам бы хотел узнать 8 ноя 2015 в 12:28
  • Не знаю, в том то и дело. Это сервер проверяет. Условие я выложил и мое решение вроде бы ему соответствует. Не знаю в какую сторону копать
    – advortsov
    8 ноя 2015 в 12:29
  • Где проверяется 8 ноя 2015 в 12:29
  • на stepic.org, но это закрытое задание
    – advortsov
    8 ноя 2015 в 12:32

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.