重写标准函数,它是类的友元
Override standard function which is friend of class
有这样的类:
#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
,你是overload
。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
基本上,你不能这样做。首先,不允许在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) {
//...
}
}
相关文章:
- C++模板来检查友元函数的存在
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何在嵌套类中正确使用友元声明?
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 将子类方法声明为基类的友元
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- 友元方法作为常量
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 在为嵌套类定义行外友元时,我真的必须打破封装吗?
- 未定义的类模板不会实例化以检查友元函数
- 为什么标准禁止部分专门化的友元声明
- 重写标准函数,它是类的友元