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

发布于 2024-07-08 18:07:23 字数 247 浏览 18 评论 0原文

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

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

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

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

.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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

叹梦 2024-07-15 18:07:24

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

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.

画骨成沙 2024-07-15 18:07:23

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

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

对于以下代码:

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

explicit foo::foo(int) {}

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

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) {}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文