gpt4 book ai didi

c++ - 在类内部定义 friend 用户定义的文字运算符

转载 作者:行者123 更新时间:2023-11-28 02:06:12 27 4
gpt4 key购买 nike

为什么在类 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;
}

可以定义相同的 friend 用户定义文字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;
}

该标准的引用是否有影响?

A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not

最佳答案

您遇到的问题是,来自 [namespace.memdef]:

The friend declaration does not by itself make the name visible to unqualified lookup (3.4.1) or qualified lookup (3.4.3).

找到它们的方式是通过参数依赖查找,[basic.lookup.argdep]:

When considering an associated namespace, the lookup is the same as the lookup performed when the associated namespace is used as a qualifier (3.4.3.2) except that: [...] Any namespace-scope friend functions or friend function templates declared in associated classes are visible within their respective namespaces even if they are not visible during an ordinary lookup (11.3).

std::ostream& operator<< (std::ostream& o, test t)由于对第二个参数的参数依赖查找而被发现。

当您定义 _UNIT在类的外部,它使函数可见。

但是,当您定义 _UNIT内联 - 它对普通查找不可见,唯一的参数 ( double ) 没有任何关联的 namespace ,因此也无法通过参数相关查找找到它。

关于c++ - 在类内部定义 friend 用户定义的文字运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328444/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com