I see a few things wrong:
using namespace std;
Get out of the habit of using that. See Why is "using namespace std" considered bad practice?.
double comparePrices(const Vehicle&, Vehicle&);
comparePrices()
is a non-static
method, which means you need to call it on a Vehicle
object, as well as pass in two Vehicle
objects as input parameters. That is a bit wasteful and redundant. Either make comparePrices()
static, or else remove one of the Vehicle
parameters and use the implicit this
parameter to access the object being called on.
Also, just from a design perspective, comparePrices()
should not be prompting the user for input. That job belongs in main()
before calling comparePrices()
.
cout << "Used car price is $" << usedCar.setPrice();
setPrice()
takes a double
as input, but you are not passing in a double
value. That is what the compiler error is complaining about.
Also, setPrice()
does not have a return value, its return type is void
, so you can't pass it to operator<<
. You need to add a separate getPrice()
method to the Vehicle
class to return its price
member.
With that said, try this instead:
#include <iostream>
class Vehicle
{
private:
double price = 0;
public:
double getPrice() const
{
return price;
}
void setPrice(double p)
{
price = p;
}
static double comparePrices(const Vehicle&, const Vehicle&);
};
double Vehicle::comparePrices(const Vehicle& v1, const Vehicle& v2)
{
return v1.price - v2.price;
}
int main()
{
Vehicle newCar, usedCar;
double price, diff;
newCar.setPrice(38000);
std::cout << "Enter the price for the used car: ";
std::cin >> price;
usedCar.setPrice(price);
diff = Vehicle::comparePrices(newCar, usedCar);
std::cout << "Used car price is $" << usedCar.getPrice();
std::cout << ", the difference is $" << diff << std::endl;
return 0;
}
Or this:
#include <iostream>
class Vehicle
{
private:
double price = 0;
public:
double getPrice() const
{
return price;
}
void setPrice(double p)
{
price = p;
}
double comparePrices(const Vehicle&);
};
double Vehicle::comparePrices(const Vehicle& other)
{
return price - other.price;
}
int main()
{
Vehicle newCar, usedCar;
double price, diff;
newCar.setPrice(38000);
std::cout << "Enter the price for the used car: ";
std::cin >> price;
usedCar.setPrice(price);
diff = newCar.comparePrices(usedCar);
std::cout << "Used car price is $" << usedCar.getPrice();
std::cout << ", the difference is $" << diff << std::endl;
return 0;
}