当 C++ 中函数参数的输入类型(类)错误时的错误处理

Error handling when wrong type(class) of input to the function argument in C++

本文关键字:错误 处理 输入 C++ 函数 参数 类型      更新时间:2023-10-16

我有一个名为 Fruit 的类包含一些函数:

Class Fruit {
Fruit(); //some constructer 
int countFruit(Fruit n); //some function
}

假设我有另一个名为Vegetable的类,其构造方式与 Fruit 相同。在函数int Fruit::countFruit(Fruit input(中,我只允许类水果的变量是有效的输入,如果用户不小心扔进了类蔬菜的变量,该函数应该能够检测到这一点,并<<"错误的输入"。

问题是,我应该如何编写我的函数?

int Fruit::countFruit(Fruit n){
if () // i want to say if n is not class Fruit
cout << "wrong input";

不知道为什么要这样做;我宁愿在编译时知道函数何时被错误使用。 但是要回答这个问题,您可以重载countFruit方法。

Class Fruit {
Fruit(); //some constructer 
int countFruit(Fruit n); //some function
int countFruit(vegetable n); // overloaded function
}
int Fruit::countFruit(vegetable n){
cout << "wrong input";
return -1;
}