2016-10-18 87 views
0

讓我們考慮的定義:C++獲取類成員的默認值,而無需創建新的對象

struct ClassWithMember 
{ 
    int myIntMember = 10; 
} 

我想得到myIntMember的默認值,但不創建另一個類的實例

// IMPOSSIBLE int myInt = ClassWithMember::myIntMember; 
// MUST AVOID int myInt = ClassWithMember().myIntMember; 

我知道解決辦法,但不喜歡:

struct ClassWithMember 
{ 
    static const int myIntMember_DEFAULT = 10; 
    int myIntMember = myIntMember_DEFAULT; 
} 
int myInt = ClassWithMember::myIntMember_DEFAULT; 

因爲它需要額外的線。而且我無法定義像static const int *const INTEGER11_DEFAULT = 0x100088855;這樣的內聯靜態指針,這樣的指針必須在.cpp文件中定義,在.hpp中只是聲明。我的許多課程只有標題,因此爲此值創建多餘的.cpp不是個好主意。

Here是C#

+1

「我知道解決方法,但不喜歡它」....可能是你應該解釋爲什麼? – HazemGomaa

+0

因爲它需要多一行。我不能像'static const int * const INTEGER11 = 11;'那樣定義內聯靜態指針,指針必須在'.cpp'文件中定義,僅在'.hpp'聲明中定義。 – kyb

+0

「static const int * const INTEGER11 = 11」不是有效語句,這與上面提到的所有關於可訪問性的問題都不相同......請編輯您的問題以符合您的真正需求。 – HazemGomaa

回答

1

了類似的問題,我把這個解決方案解決辦法

struct ClassWithMember 
{ 
    static const int myIntMember_DEFAULT = 10; 
    int myIntMember = myIntMember_DEFAULT; 
} 
int myInt = ClassWithMember::myIntMember_DEFAULT; 

爲指針,它看起來更復雜

//.hpp 
struct ClassWithMember 
{ 
    static AnotherClass* const myMember_DEFAULT; //=X; Assignment not allowed 
    AnotherClass* myMember = myMember_DEFAULT; 
} 
//.cpp 
AnotherClass* const MyNamespace::ClassWithMember::myMember_DEFAULT = pAnotherInstance; 
//usage 
auto *my = ClassWithMember::myMember_DEFAULT; 
2

我想,對於你,只是另一種解決方法,但我認爲是一點點(只有一點)更實用。

如果將默認值保存爲靜態方法返回的靜態常量,則可以避免cpp文件中出現額外的行。

下面的例子做一個模板包裝的伎倆(默認值與默認vaule模板參數,只是爲了好玩),但模板部分只是爲了避免在這個例子中的代碼重複

#include <iostream> 

template <typename T, T defTpl = T{}> 
struct wrapperWithDef 
{ 
    static T getDefVal() 
    { static T const def { defTpl }; return def; } 

    T myTMember { getDefVal() }; 
}; 

int main() 
{ 
    wrapperWithDef<int>   wi; 
    wrapperWithDef<long, 3L>  wl; 
    wrapperWithDef<int *>  wp; 

    // print "0, 3, (nil)" (clang++) or "0, 3, 0" (g++) 
    std::cout << wi.myTMember << ", " << wl.myTMember << ", " 
     << wp.myTMember << std::endl; 

    // print "5, (nil), 1" (clang++) or "5, 0, 1" (g++) 
    std::cout << wrapperWithDef<unsigned, 5U>::getDefVal() << ", " 
     << wrapperWithDef<long *>::getDefVal() << ", " 
     << wrapperWithDef<bool, true>::getDefVal() << std::endl; 

    return 0; 
} 
相關問題