C++ constructor without parameter name [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-13 04:57:55

问题


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)
}

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?


回答1:


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 also triggers this explicative warning:

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.



来源:https://stackoverflow.com/questions/26336825/c-constructor-without-parameter-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!