Hello everybody!
I'm trying to display the result of difference of two-dimensional vectors using friend overloading. Builder shows the following error after compilation (line 40). What should I change for in my code in order to find the problem?
Thanks in advance.

[C++ Error] 05_Part.cpp(40): E2034 Cannot convert 'double' to 'Vector2D'

#include <iostream.h>
#include <conio.h>

class Vector2D {

double x, y;

friend Vector2D operator- ( const Vector2D &, const Vector2D & );

public:

friend ostream & operator << (ostream & os, const Vector2D & cv)
  {  os << cv.x << ',' << cv.y;
      return os;
  }

};

Vector2D operator- ( const Vector2D & vector1, const Vector2D & vector2 ) {
        Vector2D vector_tmp = vector1;
        vector_tmp.x -= vector2.x;
        vector_tmp.y -= vector2.y;
        return vector_tmp;
        }

int main()
{
double a1, b1;
double a2, b2;

cout << "Enter the first two-dimensional vector: ";
cin >> a1;
cin >> b1;

cout << "Enter the second two-dimensional vector: ";
cin >> a2;
cin >> b2;

// vector declaration
Vector2D a(a1, b1);
Vector2D b(a2, b2);

cout << "Vector #1: " << a << endl;
cout << "Vector #2: " << b << endl;

// vector difference
Vector2D d = a - b - Vector2D(3.0, 9.0);
cout << "Difference is equal " << d << endl;

getch();
return 0;
}

First, you're doing yourself no favours by using a compiler from twenty years ago. C++ has moved on a long way since then, and you'd be much better using a recent compiler.

Anyway, you're trying to create a Vector2D object using this function:
Vector2D a(a1, b1);
This is a constructor of Vector2D that takes two parameters, each one a double. The problem is that no such constructor exists. You have to write it yourself.

How to make constructor for this? Is this concept right? (It is not working)

Vector2D Vector2D:: operator- ( const Vector2D & vector ) const
{
        Vector vector_tmp = *this;
        vector_tmp.x -= vector.x;
        vector_tmp.y -= vector.y;
        return vector_tmp;
        }

That looks like an attempt to make a copy constructor. You're not trying to use that. You're trying to use this constructor:

Vector2D::Vector2D (double xVal, double yVal)
{
  x = xVal;
  y = yVal;
}

Hey Moschops! Thank you so much for your insight, your explanation makes it more clear to me.
Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.