如果我使用显式构造函数,是否需要将关键字放在.h和.cpp文件中

If I use explicit constructor, do I need to put the keyword in both .h and .cpp files?

本文关键字:关键字 文件 cpp 是否 构造函数 如果      更新时间:2023-10-16

实际上我的问题都在标题中
无论如何:
我有一个类,我使用显式构造函数:
.h

class MyClass
{
  public:
    explicit MyClass(const string& s): query(s) {}
  private:
   string query;
}

是否必须在实现(.cpp)文件中放入显式关键字?

不,不是。explicit关键字只允许在标头中使用。我的gcc说:

test.cpp:6: error: only declarations of constructors can be 'explicit'

对于以下代码:

class foo {
public:
    explicit foo(int);
};
explicit foo::foo(int) {}

关于后续问题(您确实应该将其作为单独的问题提交),初始化列表与构造函数的实现(其函数体)一起提供,该实现可能在头文件或cpp文件中。