这是一个简单的体重转换程序。目的是将EnglishWeight1除以5磅12盎司的数字。 我使用try-throw-catch方法处理除以0的问题。
请帮助。
//Class Declaration
class EnglishWeight
{
private:
int pounds, ounces;
public:
EnglishWeight(void); //0-argument constructor
EnglishWeight(int lbs, int oz);
EnglishWeight ScalarDivision(const int &s, int *check) const;
};
//Member Function Definition
EnglishWeight::EnglishWeight(void)
{
pounds = ounces = 0;
}
EnglishWeight::EnglishWeight(int lbs, int oz)
{
pounds = lbs;
ounces = oz;
}
EnglishWeight EnglishWeight::ScalarDivision(const int &s, int *check) const //Scalar Division function
{
EnglishWeight sdivide; //Declare variable
try
{
if (s == 0) //DIV/0 check
throw 0;
else
{
sdivide.ounces = (pounds * 16) + ounces;
sdivide.pounds = sdivide.ounces / (16 * s);
sdivide.ounces = sdivide.ounces % 16;
return sdivide;
}
}
catch (int x)
{
*check = x;
}
}
void EnglishWeight::Show() const
{
std::cout << pounds << " pounds, " << ounces << " ounces";
}
//Main Driver
int main(void)
{
EnglishWeight EnglishWeight1(5, 12);
EnglishWeight sdiv1;
int number = 0;
int flag = 1;
sdiv1 = EnglishWeight1.ScalarDivision(number, &flag);
if (flag == 0)
std::cout << "EnglishWeight1 / number = DIV/0" << std::endl;
else
{
std::cout << "EnglishWeight1 / number = ";
sdiv1.Show();
std::cout << std::endl;
}
}
错误:0xC0000005:访问冲突读取位置0x0000000000000000,这可能意味着编译器正在某处读取垃圾值。我只是不知道如何解决。
答案 0 :(得分:1)
@WhozCraig建议工作。谢谢!
“在发生div-0异常的情况下,没有指定任何返回值。因此,您基本上是对EnglishWeight1.ScalarDivision的调用者说谎,声称您将在所有代码路径上返回EnglishWeight。坦率地说,我不能理解您的编译器如何未发出有关“并非所有代码路径都提供返回值”或类似措辞的警告。
“仅按原样返回sdivide。无论如何,您的呼叫者都不会使用它”