我在阅读源代码时有一个快速的问题。 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/