[英]C++ : Using a static member function within class
我必須創建一個類,在該類中,在構造函數中,在創建實例之前先驗證參數。
為此,我想在類中創建一個靜態成員函數,以后可用於驗證用戶輸入(這就是為什么它必須是靜態的)的原因。
所以看起來像這樣:
//.h
...
public:
Constructor(const int thing);
static bool validateThing(int &thing);
...
//.cpp
Class::Constructor (const int &thing):
m_thing = thing;
{
PRECONDITION(validateThing(thing));
// the PRECONDITION macro refers to a homemade function that throws an error
// if the bool in argument is false
}
...
// Later on, in the main file
...
cout << "Enter the thing" << endl;
int thing;
cin >> thing;
cout << "This thing is ";
if (!Class::validateThing(thing))
{
cout << "not ";
}
cout << "valid." << endl;
...
當我嘗試構建類時,出現以下錯誤消息:
no matching function for call to 'Class::validateThing(int &thing)'
使這項工作我應該了解些什么?
進行以下更改:
//.h
public:
Constructor(int thing);
static bool validateThing(int thing);
//.cpp
Class::Constructor(int thing): m_thing(thing)
{
PRECONDITION(validateThing(thing));
//etc.
}
bool Class::validateThing(int thing)
{
//implement here
}
看來您沒有提供validateThing
的實現。 您還應確保聲明和定義在參數類型( const
/ non- const
,引用等)上一致,並正確初始化成員。
諸如構造函數和validateThing
類的函數應采用const&
參數。 但是對於像int
這樣的簡單類型,您也可以按值傳遞。
與其按照@iavr的建議刪除const
說明符,不如在validateThing
函數的規范中添加const
,如下所示:
//.h
...
public:
Constructor(const int thing);
static bool validateThing(const int &thing);
...
並且不要忘記實現validateThing
函數。
IMO徹底使用const
說明符是一個很好的設計。 很高興知道,並且經常很重要的一點是某些函數不會更改其參數。 當我們使用“按合同設計”並且必須關心內部和允許的類狀態時,這很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.