参考对象含糊不清?

时间:2012-08-19 19:46:29

标签: c++

这是我的程序,由于此错误而失败:对“exception”的引用不明确。

为什么?

是因为我的类名是“exception”而C ++已经有了使用名称“exeption”的其他函数吗?例如,在C ++中,我们不能使用“int”作为变量。这个逻辑是否也适用于此? 谢谢。

#include <iostream>
#include <math.h>

using namespace std;

class exception{

public:
    exception(double x,double y ,double z)
    {
    cout<<"Please input a";

    cin>>x;
    cout<<"Please input b";

    cin>>y;
    cout<<"Please input c";

    cin>>z;

    a=x;
    b=y;
    c=z;
    /*
    try{
        int sonsAge = 30;
        int momsAge = 34;
        if ( sonsAge > momsAge){
            throw 99;
        }
    }
    catch(int x)
    {
        cout<<”son cannot be older than mom, Error number :”<<x;
    }
    */
    try {
        if (a==0) {
            throw 0;
        }
        if ((b*b)-(4*a*c)<0) {
            throw 1;
        }
        cout<<"x1 is"<<(-b+sqrt(b*b-4*a*c))/(2*a)<<endl
            <<"x2 is"<<(-b-sqrt(b*b-4*a*c))/(2*a);
    } catch (int x) {
        if (x==0) {
            cout<<"Error ! cannot divide by 0";
        }
        if (x==1) {
            cout<<"The square root cannot be a negative number";
        }
    }
    };

private:
    double a,b,c;
};

int main()
{
    exception ob1(3.2,12.3,412);
    return 0;
}

2 个答案:

答案 0 :(得分:5)

std::exception是标准的类名;它是标准异常层次结构的基本类型。您可以通过将其定级为::exception来命名您自己的课程。这是不使用using namespace std的绝佳理由。

答案 1 :(得分:0)

通过语句using namespace stdstd::exception类被解析为exception。现在,您定义一个具有相同名称的类。编译器现在无法通过名称exception区分这两个类。因此,exception这个名称是暧昧的。定义引用std::exception&应该可以正常工作,因为你告诉编译器确切地使用哪个类。