在派生类中重载新运算符

Ale*_*der 1 c++ operator-overloading new-operator

new在Base类中重载了运算符.但是,当我new向Derived类添加额外的重载时,gcc编译器new在Base类中找不到运算符.为什么?

最好,亚历克斯

#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>();
}
Run Code Online (Sandbox Code Playgroud)

gcc输出:

   new.cpp: In function ‘void foo()’:
new.cpp:17:45: error: no matching function for call to ‘Derived<char>::operator new(sizetype, void*&)’
  Derived<char> *d = new (loc) Derived<char>();
                                             ^
new.cpp:17:45: note: candidate is:
new.cpp:11:10: note: static void* Derived<t>::operator new(size_t, int, void*) [with t = char; size_t = unsigned int]
   void * operator new (size_t size, int sz, void *loc) { return loc; }
          ^
new.cpp:11:10: note:   candidate expects 3 arguments, 2 provided
Run Code Online (Sandbox Code Playgroud)

vso*_*tco 5

当您operator new通过放置new表达式调用时

new (loc) Derived<char>();
Run Code Online (Sandbox Code Playgroud)

编译器operator newDerived类中查找重载(而不是Base类).它找到了它,但你的超载

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

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

如果你问为什么编译器不够智能来调用它Base的重载operator new,那是因为名称隐藏:类中的operator new重载Derived隐藏了类中的一个Base.如果要Base::operator newDerived类中显示过载,请使用

using Base<t>::operator new;
Run Code Online (Sandbox Code Playgroud)