gpt4 book ai didi

要调用的 C++ 不匹配函数

转载 作者:行者123 更新时间:2023-11-28 01:23:44 26 4
gpt4 key购买 nike

我可以知道这些代码有什么问题吗?

#include <iostream>

using namespace std;

class Vehicle
{
double price = 0;
public:
void setPrice(double p)
{
price = p;
}
double comparePrices(const Vehicle&, Vehicle&);
};

double Vehicle::comparePrices(const Vehicle& car1, Vehicle& car2)
{
cout << "Enter the price for the used car: ";
double price;
cin >> price;
car2.setPrice(price);
return car1.price - car2.price;
}

int main()
{
Vehicle newCar, usedCar;
double diff;
newCar.setPrice(38000);
diff = newCar.comparePrices(newCar, usedCar);
cout << "Used car price is $" << usedCar.setPrice();
cout << ", the difference is $" << diff << endl;
}

执行后报错

error: no matching function for call to 'Vehicle::setPrice()'|

最佳答案

我看到了一些错误:

using namespace std;

改掉使用它的习惯。参见 Why is "using namespace std" considered bad practice? .

double comparePrices(const Vehicle&, Vehicle&);

comparePrices()是非 static方法,这意味着您需要在 Vehicle 上调用它对象,以及传入两个 Vehicle对象作为输入参数。这有点浪费和多余。要么制作comparePrices()静态,否则删除其中一个 Vehicle参数并使用隐式 this访问被调用对象的参数。

此外,仅从设计角度来看,comparePrices()不应提示用户输入。该工作属于 main()打电话前comparePrices() .

cout << "Used car price is $" << usedCar.setPrice();

setPrice()需要 double作为输入,但您没有传入 double值(value)。这就是编译器错误所提示的。

此外,setPrice()没有返回值,它的返回类型是void , 所以你不能把它传递给 operator<< .您需要添加一个单独的 getPrice() Vehicle 的方法类返回其 price成员(member)。

话虽如此,试试这个:

#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;
}

或者这个:

#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;
}

关于要调用的 C++ 不匹配函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54917127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com