其他分享
首页 > 其他分享> > c – 默认情况下是否存在静态的成员函数?

c – 默认情况下是否存在静态的成员函数?

作者:互联网

重载运算符是否默认为静态?例如:

template <typename E>
class Link
{
private:
    Link<E>* freeList;
public:
    E element;
    Link<E>* next;
    Link(const E& elemVal, Link<E>* nextVal) { element = elemVal; next = nextVal; }
    Link(Link<E>* nextVal) { next = nextVal; }

    void* operator new(size_t)
    {
        Link<E>* temp=freeList;
        freeList=freeList->next;
        return temp;
    }
};

当我尝试编译它时,我收到以下错误:

Invalid use of member 'Link<E>::freeList' in static member function.

我想知道重载的operator new是否实际上是静态的.

解决方法:

是!类特定运算符new和operator delete的重载是静态成员函数.它们不能是“常规”成员函数,因为在调用它们时没有可用的实例.他们在那里(de)分配原始存储.此时没有对象实例,对于它们中的任何一个.

这在[class.free]/1中描述:

Any allocation function for a class T is a static member (even if not
explicitly declared static).

[class.free]/5

Any deallocation function for a class X is a static member (even if
not explicitly declared static).

标签:c,operator-overloading,static-methods
来源: https://codeday.me/bug/20190727/1549500.html