[英]C++: Default values in class member
我在為C ++類成員指定默認值時遇到問題。 我的代碼是:
來自Someclass.h:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool);
}
...來自SomeClass.cpp:
void SomeClass::printOut(bool foobar=true)
{
if (foobar) { std::cout << foobar << std::endl; }
}
......最后,來自main.cpp:
int main()
{
SomeClass s;
s.printOut();
return 0;
}
但是這會給出錯誤消息(gcc):
../main.cpp: In function `int main()':
../main.cpp:8: error: no matching function for call to `SomeClass::printOut()'
../SomeClass.h:18: note: candidates are: void SomeClass::printOut(bool)
subdir.mk:21: recipe for target `main.o' failed
make: *** [main.o] Error 1
我已經嘗試將默認值直接指定到頭文件中的類聲明等。我也嘗試過搜索Stack Overflow和Google,但在任何地方都找不到任何解決方案。 我究竟做錯了什么?
您沒有在標頭中指定參數的默認值,編譯器正在為您的語句s.printOut();
查找簽名void printOut(void)
的函數s.printOut();
但正確地找不到它。 你需要的是:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut( bool fValue = true ); // Note change in param in definition
}
在你的cpp:
void SomeClass::printOut(bool foobar /*=true*/ )
{
if (foobar) { std::cout << foobar << std::endl; }
}
作為旁注,請記住,您不必將參數的注釋默認值放在實現文件中,但是可讀性是個好主意。
您需要在類定義中聲明默認值,而不是在實現中聲明。
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool foobar = true); //move default here
}
void SomeClass::printOut(bool foobar) //remove from here
{
if (foobar) { std::cout << foobar << std::endl; }
}
另請注意:
SomeClass s();
沒有做你期望它做的事。 它不創建一個對象s
類型SomeClass
,但聲明的函數s
與返回類型SomeClass
。 s.printOut();
不應該編譯。
你可能想要:
SomeClass s;
必須在方法聲明中指定默認值,而不是在實現中指定。
必須在標頭中定義默認參數,如下所示:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool value = true);
}
重寫如下..注意bool b = false
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool b=false);
}
嘗試在頭文件中指定默認值:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool foobar=true);
}
必須在聲明中指定默認值,而不是在定義中指定。 您可以在兩個位置指定默認值,但不能從定義中省略。 希望我能混淆你。 我將顯示e \\更正的代碼,以便您了解:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void printOut (bool foobar = true);
}
...來自SomeClass.cpp:
void SomeClass::printOut() //or you can use: void SomeClass::printOut(bool foobar=true)
{
if (foobar) { std::cout << foobar << std::endl; }
}
......最后,來自main.cpp:
int main()
{
SomeClass s();
s.printOut();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.