c++ - 是否可以让构造函数具有与声明的类不同的名称?

标签 c++

我在阅读源代码时有一个快速的问题。 AFAIK,构造函数的名称应该与声明的类相同。但是,以下代码作为构造函数具有不同的名称。谁能告诉我为什么这段代码有效?

class directFieldMapper
:
    public FieldMapper
{
    const labelUList& directAddressing_;

    bool hasUnmapped_;

public:

    // Constructors

        //- Construct given addressing
        patchFieldSubset(const labelUList& directAddressing)
        :
            directAddressing_(directAddressing),
            hasUnmapped_(false)
        {
            if (directAddressing_.size() && min(directAddressing_) < 0)
            {
                hasUnmapped_ = true;
            }
        }

    //- Destructor
    virtual ~directFieldMapper()
    {}
}

好的,我发现这个类不在Makefile中的源代码列表中。所以,这个类永远不会被编译。

最佳答案

Is it possible to have constructor have different name as the class declared?

没有。

AFAIK, the name of a constructor should be identical to the class declared.

正确。

But, the following code has a different name as a constructor.

根据 C++ 标准,代码格式错误。

Anybody can tell me why this code works?

如果它有效,那么它是由于某种语言扩展。您可以查阅编译器的手册,了解它提供的语言扩展,以及如何启用/禁用它们。

由于格式错误,所有编译器都需要发出诊断消息,否则它们就不兼容。 GNU 编译器的示例输出:

error: ISO C++ forbids declaration of 'patchFieldSubset' with no type [-fpermissive]

         patchFieldSubset(const labelUList& directAddressing)

                                                            ^

warning: non-static reference 'const labelUList& directFieldMapper::directAddressing_' in class without a constructor [-Wuninitialized]

     const labelUList& directAddressing_;

                       ^~~~~~~~~~~~~~~~~

error: expected ';' after class definition

 }
  ^

关于c++ - 是否可以让构造函数具有与声明的类不同的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48647830/

相关文章:

c++ - 胖 std::function 的精简替换

c++ - C++ 字符串数组 append 上的 objective-c ++ 崩溃

c++ - 我可以在用 C++ 构造静态本地时访问它吗?

c++ - 从文件逐行读入 vector<T> 对于二进制数据 C++ 不正确

c++ - 有没有办法比较 C/C++ 程序的两次不同运行?

c++ - 什么时候调用继承的Constructor代码

C++ 在 8086 中获取类/结构地址

c++ - 如何在 Mac OS X 中获取 aio 信号处理程序的用户数据

c++ - 为什么不调用复制构造函数将临时对象复制到新定义的对象

c++ - STL map 在删除第一对后不会添加一对