鍍金池/ 問(wèn)答/C++/ 請(qǐng)問(wèn)這個(gè)形參的重定義的錯(cuò)誤是怎么產(chǎn)生的

請(qǐng)問(wèn)這個(gè)形參的重定義的錯(cuò)誤是怎么產(chǎn)生的

1.如圖,b類公共繼承a類,b的構(gòu)造函數(shù)會(huì)調(diào)用a的構(gòu)造函數(shù),打箭頭的地方出現(xiàn)形參i的重定義的錯(cuò)誤
圖片描述

2.但是如果把a(bǔ)(i)寫(xiě)在b的構(gòu)造函數(shù)的括號(hào)外就編譯通過(guò)(箭頭所示),這是為什么。形參的重定義出現(xiàn)的原因應(yīng)該是同名形參重復(fù)的定義,但是我沒(méi)有定義第二遍啊。

圖片描述

回答
編輯回答
失魂人

第一種語(yǔ)境下,a(i);是一個(gè)語(yǔ)句(statement),此時(shí)編譯器會(huì)把它解析成變量聲明,由此局部變量i與函數(shù)參數(shù)重名。

根據(jù)語(yǔ)法,它可以被解釋成函數(shù)式顯式類型轉(zhuǎn)換或者聲明,存在二義性。標(biāo)準(zhǔn)約定將其解釋成聲明。

9.8.1 There is an ambiguity in the grammar involving expression-statements and declarations: An expression statement with a function-style explicit type conversion (8.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.

你給出的第二種語(yǔ)境下,a(i)是ctor-initializer,不存在表達(dá)式、聲明二義性。

2018年2月11日 08:41