重载数学运算符

Overload math operators

本文关键字:运算符 重载      更新时间:2023-10-16

可能重复:
为什么我的日志在std命名空间中?

基于根据返回值重载C++函数,我做了以下实验:

#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

在CCD_ 1中的第一行上。更多的实验表明,当我将类名asin更改为Asin(或其他任何类似的名称)时,这很好,正如预期的那样。因此,很明显,我不允许调用我的类asin,而定义它(而不使用它)的行为不会给我任何警告/错误。

现在我知道这一切都是不好的做法,所以不要因此而激怒我。我问这个问题纯粹是出于学术兴趣:为什么我不能把我的班级称为asinacosatan之类的?我的印象是cmath将所有内容都隐藏在std-命名空间中,这样在全局命名空间中定义这个类就不会产生这个特定的问题。

有人能解释一下发生了什么吗?

asin是c++标准库中定义为全局函数的函数,也在数学库中定义,(因此您甚至不必使用std::)如果您尝试使用未定义的命名空间,则会出现"使用‘asin’不明确"错误。命名命名空间解决了您的问题。

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