我对这段代码中构造函数的行为感到困惑。
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),尽管你并不真正需要那个参数)。当检测到这种情况(即复制构造)时,您可能想做其他事情。