gpt4 book ai didi

c++ - 覆盖类友元的标准函数

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:27 25 4
gpt4 key购买 nike

有这样一个类:

#include <iostream>
#include <cmath>

class Element {
private:
int val;
public:
Element(int val_){ val = val_;}
friend Element std::pow(Element a, int exp);
};

我想覆盖标准函数 pow,它是类 Element 的友元,以处理我类的对象。但是编译时出现如下错误:

error: ‘Element std::pow(Element, int)’ should have been declared inside ‘std’

如何覆盖标准的 pow 函数?

最佳答案

首先,您不是覆盖,而是重载。术语override 与虚函数相关,overload 与根据参数类型选择正确的函数有关。

解决方案很简单:不要写std::pow,只写一个pow 或者yournamespace::pow,如果你愿意 - 没关系。是的,就是这样。

然后:

double a;
Element b;

using std::pow;
pow(a, 10.0); // calls std::pow(double, double)
pow(Element, 10) // calls pow(Element, int)

说明:在 C++ 中,有一个名为 ADL(或 Koenig 的查找)的疯狂事物,它基本上会决定使用哪个变体,并且它会从任何命名空间中选择重载,而无需您在调用位置指定它。

阅读: http://en.wikipedia.org/wiki/Argument-dependent_name_lookup

关于c++ - 覆盖类友元的标准函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6859934/

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