【问题标题】:C++ - Throw Erorr MessageC++ - 抛出错误信息
【发布时间】:2019-12-03 14:41:38
【问题描述】:

main() 函数应该显示一个适当的 如果为任何一个输入非数字或负值,则抛出错误消息 数据成员。

谁能帮我写main函数

这是我的代码

#include <iostream>
using namespace std;

class RealEstate
{
private:
    int price;
    int bedroomNumb;
    int bathsNumb;

public:
    RealEstate(int p, int bed, int bath)
    {
        price = p;
        bedroomNumb = bed;
        bathsNumb = bath;
    }
    friend ostream &operator<<(ostream &out, const RealEstate &r);
    friend istream &operator>>(istream &in, RealEstate &r);
};

istream &operator>>(istream &in, RealEstate &r)
{
    cout << "Enter Real Estate Price: ";
    in >> r.price;
    cout << "Enter Numbers of Bedroom: ";
    in >> r.bedroomNumb;
    cout << "Enter Numbers of Baths: ";
    in >> r.bathsNumb;

    return in;
}

ostream &operator<<(ostream &out, const RealEstate &r)
{
    out << "Price: " << r.price << endl;
    out << "Bedroom: " << r.bedroomNumb << endl;
    out << "Baths: " << r.bathsNumb << endl;

    return out;
}

int main()
{

}

【问题讨论】:

  • 你的代码没有抛出任何东西?
  • 在发生异常情况并在调用堆栈(或没有)的某个地方捕获异常时抛出异常。仅修改main 以引发异常在这里并没有真正意义。是否有可能其他代码应该抛出您应该在main 中捕获的异常?
  • 有一些功能添加到我的代码?我的意思是会被抛出的函数?

标签: c++ throw


【解决方案1】:

据我了解,您希望在 main() 中进行一些尝试和捕获,并抛出接受用户输入的函数。如果是这种情况,您绝对应该在函数中使用 throw 关键字。在你的主要,你会

int main(){
    try{
       function() //note that the function you are calling here should throw an error of type char* and throw this error if the number input by the user is negative and non-numeric. 
    }catch(const char* msg)
}

这是对如何实施错误处理的简要说明(鉴于您提供的程序和信息)。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    相关资源
    最近更新 更多