【问题标题】:Overload math operators [duplicate]重载数学运算符 [重复]
【发布时间】:2012-09-24 10:25:50
【问题描述】:

可能重复:
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-namespace 中的所有内容,因此在全局命名空间中定义这个类不会产生这个特殊问题。

谁能解释发生了什么?

【问题讨论】:

标签: c++ operator-overloading


【解决方案1】:

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

【讨论】:

  • 谢谢,虽然当我不考虑 cmath 时,我没有 asin - 我猜这取决于编译器。我认为真正的问题是:为什么在全局命名空间中重新定义asin 不会导致错误?
【解决方案2】:

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

【讨论】:

  • 那么有没有办法手动排除这些定义?我只需要在不同的命名空间中定义我的东西吗?
  • 我主要在带有 gcc 的 Linux 上进行编码;我对 Visual Studio 不是很精通。 VS 不包含它,但随后“隐藏”在 windows.h 之类的东西中?
  • @AJMansfield 我认为您不能简单地排除它们。你应该使用命名空间。
  • @Rody Oldenhuis:不包括 windows.h。不幸的是,我找不到已经为 msvc 定义的函数列表,但我认为它主要是数学函数。
猜你喜欢
  • 2021-02-11
  • 2015-08-22
  • 2014-02-25
  • 2015-06-20
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多