1

Possible Duplicate:
Why is my log in the std namespace?

Based on Overload a C++ function according to the return value, I did the following experiment:

#include <cmath>

class myType
{
private:
    double value;
    myType(double value) : value(value) {}

public:

    myType& operator= (const myType& other) {
        if (this != &other) value = other.value;
        return *this;
    }

    static myType test(double val) { return myType(val); }

    friend std::ostream& operator<<(std::ostream& target, const myType& A);    
};

std::ostream& operator<<(std::ostream& target, const myType& A){
    target << A.value;
    return target;
}

class asin {
private:
    double value;
public:
    asin(double value)
        : value(std::asin( (value<-1.0) ? -1.0 : (value>1.0?1.0:value) ))
    {}
    operator double() { return value;               }
    operator myType() { return myType::test(value); }        
};


int main(int argc, char *argv[])
{
   myType d = asin(1.0); 

   std::cout << d << std::endl;

   return 0;
}

which resulted in

error: ‘myType::myType(double)’ is private

on the first line in main(). A bit more experimenting showed me that this works fine and as expected when I change the classname asin to Asin (or anything else for that matter). So apparently, I'm not allowed to call my class asin, while the act of defining it (and not using it) does not give me any warning/error.

Now I know all of this is bad practice, so don't flame me for that. I ask this purely out of academic interest: why can't I call my class asin, or acos or atan or anything like that? I was under the impression that cmath hid everything in the std-namespace, so that defining this class in the global namespace would not give rise this particular problem.

Can anyone explain what's going on?

4

2 回答 2

1

asin 是在 c++ 标准库中定义为全局函数,也在数学库中定义,(所以你甚至不必使用 std::) 如果你尝试使用未命名的命名空间,那么你会得到'使用 `asin' 是模棱两可的'错误。命名空间可以解决您的问题。

于 2012-09-24T17:22:59.707 回答
-1

对于某些 IDE,例如 Visual Studio,您甚至不需要包含 cmath。它已经在全局命名空间中定义了这些函数。尝试排除 cmath ,您会看到 asin() 仍然被定义。

于 2012-09-24T11:03:30.167 回答