[英]Why does this program hang?
我有以下代碼似乎導致無限循環:
struct X
{
void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};
struct X2 : X
{
void my_func( char value ) { my_func(value); }
};
它有什么問題?
第二位是無限遞歸的:
struct X2 : X
{
void my_func( char value ) { my_func(value); } //calls itself over and over again
};
使用基類的名稱前綴my_func
,您就可以了
struct X2 : X
{
void my_func( char value ) { X::my_func(value); }
};
編輯剛剛意識到基類
my_func
的簽名是不同的。
C ++編譯器靜態地解析函數重載,這意味着它將選擇最適合參數類型的函數,這就是它調用
char
重載的原因。
例如:
char cChar = 'a'; myfunc(cChar); void myfunc(char a){} //<-- this one is called void myfunc(int a){} int iInt = 1; myfunc(iInt); void myfunc(char a){} void myfunc(int a){} //<-- this one is called
謝謝Charles Bailey。 上面的代碼在這種情況下不適用,因為X2
的my_func
隱藏了基類的my_func
。 這留下了使用類名限定函數的唯一解決方案。
void my_func( char value ) { my_func(value); }
您傳遞的value
是char
因此它解析為調用相同的方法並接受char
參數。 它變成了無限循環。
void my_func( char value ) { my_func(value); }
就在那里,你已經寫了一個沒有基本情況的遞歸函數。 我不太了解C ++,但是你需要以某種方式指定你想要調用X的my_func,而不是X2(我假設你想要這樣做。)
編輯:要修復它,您需要將值轉換為int
程序進入無限循環。 my_func()調用自身,沒有條件退出它。
你的調用my_func(value)是遞歸的。 你的意思是super :: my_func(value)?
您需要顯式調用基類的函數,即:
struct X
{
void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};
struct X2 : X
{
void my_func( char value ) { X:my_func(value); }
};
默認情況下,編譯器使用同一個類中的函數(如果存在),因為它無法知道您實際想要使用哪個函數。 通過在派生類的方法中指定BaseClass::Function
,編譯器將顯式創建對該基類的方法的調用,即使您已重寫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.