c++ - 重载数学运算符

标签 c++ operator-overloading

<分区>

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

基于 Overload a C++ function according to the return value ,我做了以下实验:

#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;
}

结果是

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

main() 的第一行。更多的实验表明,当我将类名 asin 更改为 Asin (或与此相关的任何其他内容)时,这工作正常并且符合预期。显然,我不允许调用我的类 asin,而定义它(而不是使用它)的行为不会给我任何警告/错误。

现在我知道所有这些都是不好的做法,所以不要因此而责备我。我问这个纯粹是出于学术兴趣:为什么我不能称我的类为 asinacosatan 或类似的名称?我的印象是 cmath 隐藏了 std 命名空间中的所有内容,因此在全局命名空间中定义此类不会引起这个特殊问题。

谁能解释一下这是怎么回事?

最佳答案

asin 是一个在 c++ 标准库中定义为全局函数,也在 math 库中定义,(所以你甚至不必使用 std::) 如果你尝试使用未命名的命名空间,那么你会得到“使用‘asin’是不明确的”错误。 命名空间可以解决您的问题。

关于c++ - 重载数学运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12563122/

相关文章:

c++ - Eclipse IDE Arduino (Sloeber) C++ String in class error does not name a type

C++ 比较运算符重载常量与非常量行为

c++矩阵重载不起作用

c++ - 为什么程序因错误 exc_bad_access code=exc_i386_gpflt 而中断

c++ - QMap::insertMulti 还是 QMultiMap?

c++ - 在通用 C++ 代码中移动基于范围的循环?

c++ - 为什么在 OpenGL 中显式管理矩阵更好?

c++ - 为什么我的赋值运算符不能用于自赋值?

c++ - 实现全功能的移位流语法

c++ - 运算符仅以一种方式定义 - C++