重载数学运算符
Overload math operators
可能重复:
为什么我的日志在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
,而定义它(而不使用它)的行为不会给我任何警告/错误。
现在我知道这一切都是不好的做法,所以不要因此而激怒我。我问这个问题纯粹是出于学术兴趣:为什么我不能把我的班级称为asin
、acos
、atan
之类的?我的印象是cmath
将所有内容都隐藏在std
-命名空间中,这样在全局命名空间中定义这个类就不会产生这个特定的问题。
有人能解释一下发生了什么吗?
asin是c++标准库中定义为全局函数的函数,也在数学库中定义,(因此您甚至不必使用std::)如果您尝试使用未定义的命名空间,则会出现"使用‘asin’不明确"错误。命名命名空间解决了您的问题。
对于某些IDE,例如Visual Studio,甚至不需要包含cmath。它已经在全局命名空间中定义了这些函数。尝试排除cmath,您会发现asin()仍然是定义的。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板