【发布时间】:2012-09-24 10:25:50
【问题描述】:
基于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,而定义它(而不是使用它)的行为不会给我任何警告/错误。
现在我知道所有这些都是不好的做法,所以不要因此而抨击我。我问这个纯粹是出于学术兴趣:为什么我不能给我的班级打电话asin、acos 或atan 或类似的东西?我的印象是cmath 隐藏了std-namespace 中的所有内容,因此在全局命名空间中定义这个类不会产生这个特殊问题。
谁能解释发生了什么?
【问题讨论】:
-
@JesseGood:感谢您找到副本。
-
反对者是否愿意发表评论?