简体   繁体   English

重载派生类中的新运算符

[英]Overloading new operator in the derived class

I have overloaded new operator in the Base class. 我在Base类中重载了new运算符。 However, when I add additional overloaded new to the Derived class gcc compiler does not find new operator in the Base class. 但是,当我向Derived类添加其他重载new gcc编译器时,在Base类中找不到new运算符。 Why? 为什么?

Best, Alex 最好,亚历克斯

#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>();
}

gcc output: 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

When you invoke the operator new via the placement new expression 通过放置new表达式调用operator new

new (loc) Derived<char>();

the compiler looks for an overload of operator new in the Derived class (and not the Base class). 编译器会在Derived类(而不是Base类)中查找operator new的重载。 It finds it, but your overload 找到了,但是你超载了

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

accepts more parameters, hence the error. 接受更多参数,因此会出现错误。

If you ask why the compiler is not smart enough to invoke the Base 's overload of operator new , it is because of name hiding : the operator new overload in the Derived class hides the one of the Base class. 如果您问为什么编译器不够聪明,无法调用operator newBase重载,这是因为名称隐藏Derived类中的operator new重载隐藏了Base类之一。 If you want to make the Base::operator new overload visible in your Derived class, use 如果要使Base::operator new重载在Derived类中可见,请使用

using Base<t>::operator new;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM