2016-06-22 159 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

啊,我現在看到了,我沒有包括任何東西,所以''不包括在內。 –