2016-06-22 160 views
1

我有以下代码:构造函数nulltpr_t:函数定义不声明参数

class C { 
private: 
    void *data; 

public: 
    constexpr C(nullptr_t) : data(nullptr) { } 
    C(int i) : data(new int(i)) { } 
}; 

我已经创建了一个构造函数,需要nullptr_t,这样我可以有类似于下面的代码:

C foo(2); 
// ... 
foo = nullptr; 

与此类似的代码以前在MSVC上工作过,但是此代码无法在GCC 5.3.1(使用-std=c++14)上编译,而在C(nullptr_t)的右括号与error: function definition does not declare parameters之间编译。即使我给参数一个名字(在这种情况下,_),我得到error: expected ')' before '_'。如果constexpr关键字被删除,这也会失败。

为什么我无法声明这样的构造函数,以及有什么可能的解决方法?

+1

您应该'的#include '至少。 (并添加'std ::'。) – songyuanyao

+0

@songyuanyao谢谢你,修正了它。 –

回答

1

您必须是 “使用命名空间std” 迷,你just got tripped up by it

constexpr C(std::nullptr_t) : data(nullptr) { } 

GCC 5.3.1编译此,在--std=c++14一致性级别:

[[email protected] tmp]$ cat t.C 
#include <iostream> 

class C { 
private: 
    void *data; 

public: 
    constexpr C(std::nullptr_t) : data(nullptr) { } 
    C(int i) : data(new int(i)) { } 
}; 
[[email protected] tmp]$ g++ -g -c --std=c++14 -o t.o t.C 
[[email protected] tmp]$ g++ --version 
g++ (GCC) 5.3.1 20160406 (Red Hat 5.3.1-6) 
Copyright (C) 2015 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
+0

我刚刚尝试过,但仍然失败,出现同样的错误。你指定任何额外的标志g ++? cpp.sh也显示它:http://cpp.sh/7ldzs –

+0

不,没有额外的参数。我更新了我的答案,以证明这一点。 –

+1

啊,我现在看到了,我没有包括任何东西,所以''不包括在内。 –