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

时间:2022-06-05 22:45:25

Actually my question is all in the title.
Anyway:
I have a class and I use explicit constructor:
.h

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

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

Is it obligatory or not to put explicit keyword in implementation(.cpp) file?

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

2 个解决方案

#1


22  

No, it is not. The explicit keyword is only permitted in the header. My gcc says:

不它不是。 explicit标识符只允许在标题中使用。我的gcc说:

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

for the following code:

对于以下代码:

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

explicit foo::foo(int) {}

#2


0  

Re the followup question (which you really should have submitted as a separate question), the initialization list goes with the constructor's implementation (its function body), which might be in either the header or the cpp file.

回答后续问题(你真的应该作为一个单独的问题提交),初始化列表与构造函数的实现(它的函数体)一起使用,它可能位于头文件或cpp文件中。

#1


22  

No, it is not. The explicit keyword is only permitted in the header. My gcc says:

不它不是。 explicit标识符只允许在标题中使用。我的gcc说:

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

for the following code:

对于以下代码:

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

explicit foo::foo(int) {}

#2


0  

Re the followup question (which you really should have submitted as a separate question), the initialization list goes with the constructor's implementation (its function body), which might be in either the header or the cpp file.

回答后续问题(你真的应该作为一个单独的问题提交),初始化列表与构造函数的实现(它的函数体)一起使用,它可能位于头文件或cpp文件中。