【问题标题】:If I use explicit constructor, do I need to put the keyword in both .h and .cpp files?如果我使用显式构造函数,是否需要将关键字放在 .h 和 .cpp 文件中?
【发布时间】:2010-09-21 09:05:21
【问题描述】:

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

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

explicit 关键字是否必须放在 implementation(.cpp) 文件中?

【问题讨论】:

    标签: c++ explicit-constructor


    【解决方案1】:

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

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

    以下代码:

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

    【讨论】:

    • 我明白他的意思......我只是读了中间的那一行。
    • 我的 MS VC++ (2012) 说:'test.cpp(6): error C2071: foo::{ctor} : 非法存储类'
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多