没有参数名称的C++构造函数

标签 c++ constructor

<分区>

我对这段代码中构造函数的行为感到困惑。

class htc {
  public:
  htc() { std::cout << "HTC_FOO_CONSTRUCTOR" << std::endl ;}
  htc(const htc&) { std::cout << "HTC_BAR_CONSTRUCTOR" << std::endl;};
};

int main() 
{
  htc one; // This outputs HTC_FOO_CONSTRUCTOR
  htc two(); // This outputs nothing 
  htc three(one)
}

几个问题在 htc two() 中使用括号是什么意思? & 在构造函数 htc(const htc&) 中没有参数名称可以吗?如果是,这样的构造函数有什么用?

最佳答案

你是在声明一个函数,而不是调用一个构造函数:

class htc {
  public:
  htc() { std::cout << "HTC_FOO_CONSTRUCTOR" << std::endl ;}
  htc(const htc&) { std::cout << "HTC_BAR_CONSTRUCTOR" << std::endl;};
};

int main() 
{
  htc one; // This outputs HTC_FOO_CONSTRUCTOR
  htc two(); // Function declaration
  htc three(one); // Outputs HTC_BAR_CONSTRUCTOR
}

clang 还会触发此解释性警告:

warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]

旁注:不确定您是否指的是 default 的动态分配/value初始化。

对于你的第二个问题:拥有一个没有正式参数名称的构造函数是完全可以接受的(通常这样做是为了符合接口(interface),尽管你并不真正需要那个参数)。当检测到这种情况(即复制构造)时,您可能想做其他事情。

关于没有参数名称的C++构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26336825/

相关文章:

java - 在构造函数中初始化

c++ - SwapBuffers 导致重绘

c++ - 为契约(Contract)指定违规处理程序

C++ 长 switch 语句还是用 map 查找?

C++ 对数组进行排序

python - 为什么我们需要 __init__ 来初始化一个 python 类

java - 模板构造函数,并在主类中创建一个对象

c++ - 瓦片引擎性能问题

kotlin - kotlin 中的 init block 和构造函数有什么区别?

c# - 为什么 BaseController 的重载构造函数没有被执行?