在派生类中重载新运算符

时间:2015-11-17 15:26:07

标签: c++ operator-overloading new-operator

我在Base类中重载了 for (int i=0;i < al.size();i++){ String currentValue = al.get(i); String[] partsOfCurrentValue = currentValue.split(","); for (String part : partsOfCurrentValue) { If (part.trim().startsWith("Content")) { String[] partsOfContent = part.split(":"); String valueOfContent = partsOfContent[1]; Log.i("Value of element "+i, valueOfContent); break; } } } 运算符。但是,当我向Derived类添加额外的重载new时,gcc编译器在Base类中找不到new运算符。为什么呢?

最佳,   亚历克斯

new

gcc输出:

#include <stdlib.h>
template <class t> class Base {
  public:
    Base() {}
    void * operator new (size_t size, void *loc) { return loc; }
};

template <class t> class Derived : public Base<t> {
  public:
    Derived() {}
    void * operator new (size_t size, int sz, void *loc) { return loc; }

};

void foo() {
  void *loc = malloc(sizeof(Derived<char>));
  Derived<char> *d = new (loc) Derived<char>();
}

1 个答案:

答案 0 :(得分:5)

通过展示位置operator new表达式

调用new
new (loc) Derived<char>();

编译器在operator new类(而不是Derived类)中查找Base的重载。它找到了,但你的重载

void * operator new (size_t size, int sz, void *loc) { return loc; }
//                                ^ additional parameter

接受更多参数,因此错误。

如果你问为什么编译器不够聪明,无法调用Base operator new的重载,那是因为name hidingoperator new Derived类中的重载隐藏了Base类中的一个。如果您想在Base::operator new课程中看到Derived重载,请使用

using Base<t>::operator new;