对对象模糊的引用

  • 本文关键字:引用 模糊 对象 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;
}

std::exception是一个标准类名;它是标准异常层次结构的基本类型。您可以通过将自己的类限定为::exception来命名它。这是不使用using namespace std的一个很好的理由。

通过语句using namespace stdstd::exception类被解析为exception。现在定义一个具有相同名称的类。编译器现在无法通过名称exception来区分这两个类。因此,名称exception是模糊的。定义引用std::exception&应该像告诉编译器要使用哪个类一样有效。

最新更新