重写标准函数,它是类的友元

Override standard function which is friend of class

本文关键字:友元 标准 函数 重写      更新时间:2023-10-16

有这样的类:

#include <iostream>
#include <cmath>
class Element {
private:
  int val;
public:
  Element(int val_){ val = val_;}
  friend Element std::pow(Element a, int exp);
};

我想重写标准函数pow,它是类元素的朋友,与我的类的对象一起工作。但是,在编译过程中出现以下错误:

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

如何重写标准函数?

首先,你不是override,你是overloadoverride是指虚函数,overload是指根据参数类型选择合适的函数。

解决方案很简单:不写std::pow,只写powyournamespace::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

基本上,你不能这样做。首先,不允许在std名称空间中放置用户定义的东西。

您需要编写自己的pow函数,该函数不在std中。

一开始你不应该在命名空间std中添加东西。

您的pow重载应该在一个单独的命名空间中。你应该是

using std::pow
using my::pow;

我赞同的有争议的风格点:像这样的泛型函数不应该是命名空间限定的。也就是说,在客户端代码中使用using并调用pow()而不是std::pow(),同样适用于std::swap和其他自定义点。

唯一可以扩展std命名空间的时候是使用模板专门化。再次以std::swap为例。

必须在标准名称空间中定义函数,否则它不存在:

namespace std {
    Element pow(Element a, int exp) {
        //...
    }
}