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)
当您operator new
通过放置new
表达式调用时
new (loc) Derived<char>();
Run Code Online (Sandbox Code Playgroud)
编译器operator new
在Derived
类中查找重载(而不是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 new
在Derived
类中显示过载,请使用
using Base<t>::operator new;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
476 次 |
最近记录: |