【发布时间】:2016-05-19 15:56:33
【问题描述】:
为什么要在 give error 类中定义用户定义的文字?
class test
{
long double x;
public:
friend test operator""_UNIT(long double v)
{
test t;
t.x = v;
return t;
}
};
int main()
{
test T = 10.0_UNIT;
return 0;
}
错误:
unable to find numeric literal operator 'operator""_UNIT'
注意:可以在类中定义any friend function。
class test
{
int x;
public:
test():x(10) {}
friend std::ostream& operator<< (std::ostream& o, test t)
{
o << t.x ;
return o;
}
};
int main() {
test T;
std::cout << T;
return 0;
}
同一个朋友用户定义的文字可以定义为outside the class。
class test
{
long double x;
public:
friend test operator""_UNIT(long double v);
};
test operator""_UNIT(long double v)
{
test t;
t.x = v;
return t;
}
int main()
{
test T = 10.0_UNIT;
return 0;
}
标准中的这句话有影响吗?
类中定义的友元函数在 定义它的类。在外部定义的友元函数 类不是
【问题讨论】:
-
当您从
main()执行operator<<(std::ostream&, test)时,它必须查找函数并在test中查找,因为它是参数之一。_UNIT的唯一位置是在当前空间中,而_UNIT不存在。 -
关键区别在于
operator<<具有扩展查找的参数类型,但_UNIT没有