没有参数名称的C ++构造函数 [英] C++ constructor without parameter name

查看:121
本文介绍了没有参数名称的C ++构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am confused over the behavior of constructor in this code.

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&)中,没有参数名称可以吗?如果是的话,这样的构造函数有什么用?

Couple of questions whats the meaning of using brackets in htc two() mean? & in constructor htc(const htc&) there is no parameter name is this ok? If yes whats the use of an such constructor?

推荐答案

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

You're declaring a function, not calling a 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(); // Function declaration
  htc three(one); // Outputs HTC_BAR_CONSTRUCTOR
}

clang也会触发此显式警告:

clang also triggers this explicative warning:


警告:空括号解释为函数声明[-Wvexing-parse]

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

旁注:不确定是否使用默认值引用动态分配 / 初始化。

Sidenote: not sure if you were referring to the dynamic allocation with default/value initialization.

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

For your second question: it is perfectly acceptable to have a constructor with no formal argument name (it is often done to conform to an interface although you don't really need that parameter). You might want to do something else when such a situation (i.e. copy construction) is detected.

这篇关于没有参数名称的C ++构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆