c++ - 要调用的 C++ 不匹配函数
问题描述
我可以知道代码有什么问题吗?
#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;
}
执行后,我收到此错误
错误:没有匹配函数调用'Vehicle::setPrice()'|
解决方案
我看到一些错误的地方:
using namespace std;
摆脱使用它的习惯。请参阅为什么“使用命名空间 std”被认为是不好的做法?.
double comparePrices(const Vehicle&, Vehicle&);
comparePrices()
是一个非static
方法,这意味着您需要在一个Vehicle
对象上调用它,并传入两个Vehicle
对象作为输入参数。这有点浪费和多余。要么设为comparePrices()
静态,要么删除其中一个Vehicle
参数并使用隐式this
参数来访问被调用的对象。
另外,仅从设计的角度来看,comparePrices()
不应该提示用户输入。那份工作属于在main()
打电话之前comparePrices()
。
cout << "Used car price is $" << usedCar.setPrice();
setPrice()
将 adouble
作为输入,但您没有传入double
值。这就是编译器错误所抱怨的。
另外,setPrice()
没有返回值,它的返回类型是void
,所以你不能将它传递给operator<<
. 您需要向该类添加一个单独的getPrice()
方法以Vehicle
返回其price
成员。
话虽如此,试试这个:
#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;
}
推荐阅读
- python - 如何从 django 中的模板获取主键?
- javascript - 错误 - TypeError:无法读取未定义的属性“值”
- java - 如何在firebase上添加用户名、电子邮件和密码
- javascript - 用更少的属性构建一个新的 Javascript 对象
- javascript - React JS - 如何在 Next JS 中检测 navigator.platform
- go - 如何使用 wasm 中的 < > 运算符评估 js 值?
- python - 使用 pandas、Python 将 netCDF 中的时间变量更改为 datetime
- javascript - 将鼠标悬停在链接上时在光标位置显示图像
- php - 如何在不更改 php 中旧日期值的情况下更新日期?
- javascript - For.. of Loop 变量在异步操作中未定义