我该如何解决这个 class 问题?

How do I fix this class issue?

此代码出现 2 个错误:

'totalCost' is not a type

'cout' was not declared in this scope

我错过了什么?

#include <iostream>

class License{
public:
    int vat, totalCost;
    int calculateVat();
    };



class PurchasedLicense :public License{
    calculateVat(totalCost){ //the first error seems to be here
    vat = totalCost/10;
    return vat;
    }
};

int main()
{
    cout << "Type your license cost: "; //second is here
    cin >> calculateVat;
    cout << "Your VAT is: ";
}

可以通过为 return 类型和 calculateVat() 的参数添加类型名称来修复第一个错误。

第二个错误可以通过在 cout(和 cin)之前添加 std:: 来修复。

还有一个错误是main()函数中使用的calculateVat变量没有声明。声明该变量以修复此错误。

#include <iostream>

class License{
public:
    int vat, totalCost;
    int calculateVat();
    };



class PurchasedLicense :public License{
    // add types
    int calculateVat(int totalCost){ //the first error seems to be here
    vat = totalCost/10;
    return vat;
    }
};

int main()
{
    // declare the variable used
    int calculateVat;
    // add std::
    std::cout << "Type your license cost: "; //second is here
    std::cin >> calculateVat;
    std::cout << "Your VAT is: ";
}

除了 ,它还解释了为什么您会收到您提到的错误,以及如何解决这些错误。但是,您的代码还有其他问题。

calculateVat() 需要在 License 中标记为 virtual 以便 PurchasedLicense 覆盖它。并且您需要一个 PurchasedLicense 的对象实例供 main() 调用 calculateVat() on.

试试这个:

#include <iostream>

class License{
public:
    int vat, totalCost;
    virtual int calculateVat() = 0;
};

class PurchasedLicense : public License{
public:
    int calculateVat() override {
        vat = totalCost/10;
        return vat;
    }
};

int main()
{
    PurchasedLicense lic;
    std::cout << "Type your license cost: ";
    std::cin >> lic.totalCost;
    std::cout << "Your VAT is: " << lic.calculateVat();
}