如果函数具有相同的名称,如何调用构造函数

How to call constructor if function has the same name

本文关键字:何调用 调用 构造函数 函数 如果      更新时间:2023-10-16

如果我有以下内容:

class T
{
   public: 
      T(){}
};
void T()
{
}
int main()
{
  T(); // this calls the function, how can I call the constructor T()?
}

我对它没有任何问题,因为我可以重命名它,但只是好奇我如何强制它调用构造函数,而且我也在问自己为什么函数调用似乎比构造函数具有更高的优先级。此外,为什么没有关于重复名称的警告消息。

除了jaunchopanza所说的之外,您还可以限定呼叫:

T::T();

使用此版本,您可以创建临时文件:

class T
{
   public: 
      T(){}
};
void foo(T) {}
void T()
{
}
int main(){
   foo(T::T());
}

基本上,没有名称冲突,基本上,在不同的命名空间中

T() ==> namespace::T() It;s a function call not an object instantiation. 
T a() ==> namespace ::T::T() It;s is instantiation of T class calling the constructor.
T a() ; a() ==>namespace ::T::T()::() It;s call the functor of the T Class (need to define the operator())