c 模板的問題解析 問題2

2021-07-17 04:59:53 字數 1149 閱讀 1588

問題起源

class timer 

};class timekeeper

timekeeper(){}

std::string time;

std::string get_time()

friend

std::istream& operator>> (std::istream& is, timekeeper& sr);

};std::istream& operator>>(std::istream& is, timekeeper& sr)

int main()

上述**編譯是不會通過的,編號no3、4處**會報錯,例如gcc4.8在no.3處報錯— error: ambiguous overload for 『operator>>』 (operand types are 『std::istringstream 』 and 『timekeeper(timer (*)())』).

解答

這是c++標準的乙個特性,稱為most vexing parse。

無論是no.1還是no.2都可以被解析為乙個變數或者乙個函式宣告。

g++編譯器會認為no.3是模稜兩可的,因為如果是乙個變數則呼叫自定義的》過載,如果是乙個函式宣告,c++也提供了模板過載函式來接收anything為右值引數:

template

basic_istream&

operator>>(basic_istream&& istr, t&&);

而有些編譯器會預設這是函式宣告,而該函式型別不能繫結為右值引數,於是就會出現如下錯誤:error: cannot bind 『std::basic_istream』 lvalue to 『std::basic_istream&&』。

因此,為了避免歧義,根據實際目的no.1和no.2應做相應修改:

no.1 -> timekeeper time_keeper((timer()))

no.2 -> timekeeper time_keeper_ or timekeeper time_keeper_{} or timekeeper time_keeper_=timekeeper()

多型問題解析

首先,什麼是多型?多型 多種形態 class 動物 class 貓 extends 動物 把貓看成貓 貓 mao new 貓 常態 把貓看成動物 動物 mao new 貓 多型 把子類型別的物件看成了父類型別 貓 mao new 動物 錯誤的 多型 父類型別的引用指向了子類物件 多型的前提條件 存在...

wamp問題解析

乙個網域名稱,乙個主機,兩個專案 怎麼辦?虛擬主機 首先解析幾個隨意的網域名稱,接下來.1 啟用虛擬主機功能 開啟apache的配置檔案httpd.conf 並去掉 include conf extra httpd vhosts.conf前面的 2 找到apache conf extra下的配置檔案...

oracle in list 問題解析

解決where in list 問題,首要考慮的就是解決列表長度問題和效率問題,效率問題首要考慮繫結變數問題,另外還要考慮比如cardinality對執行計畫的影響等 declare v condition varchar2 100 v sql varchar2 1000 v count numbe...