首页 > 解决方案 > 要调用的 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()'|

标签: c++function

解决方案


我看到一些错误的地方:

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

推荐阅读