c++ - "inline operator T*() const"是什么意思?

标签 c++

我查看了一些关于 nullptr 的代码,发现:

const
class nullptr_t
{
public:
    template<class T>
    inline operator T*() const
        { return 0; }

    template<class C, class T>
    inline operator T C::*() const
        { return 0; }

private:
    void operator&() const;
} nullptr = {};

inline operator T*() constinline operator T C::*() const 是什么意思?

它们的工作方式是否与 inline T operator *() constinline T operator C::*() const 相同?

为什么不在声明中指定返回类型?

最佳答案

它们是用户定义的转换运算符函数。

一个更简单的函数:

struct Foo
{
   inline operator int () const { return 0; }
};

鉴于你可以使用

Foo f;
int i = f; // Invokes f.operator int () and initializes i with
           // return value.

对于你这个类,它是一个nullptr的匿名类,它的意思是它可以转换为任何指针或成员函数指针。您可以使用:

int* ip = nullptr;

它使用第一个用户定义的转换运算符函数的返回值来初始化ip

struct Bar
{
   void bar() {}
};

void (Bar::*ptr)() = nullptr;

它使用第二个用户定义的转换运算符函数的返回值来初始化ptr

关于c++ - "inline operator T*() const"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43440687/

相关文章:

c++ - 在 ReSharper C++ 中完成 'XML Doc Comment'

c++ - OpenCV 2质心

C++ Cout & Cin & 系统 "Ambiguous"

c# - 尝试从 COM 组件传递 BSTR* 时 C# 中的 MarshlDirectiveException

C++11 - 返回通过左值传递给函数的右值?

c++ - const 使用的内存通常比#define 多还是少?

c++ - 使用 QPrinter 打印第 x 页(共 y 页)

c++ - 为什么 "partial RVO"没有执行?

C++如何使用包含 float 的CE中的给定地址进行读/写处理?

c++ - Linux 上的 dhcp 客户端,端口或使用?