cannot bind non-const lvalue reference of type 'std::__cxx11::string&


1.問題

類的構造函數定義為:

Quote(std::string & s,double p):bookNo(s),price(p){}

如果這樣初始化對象:

Quote q("123",10);

就會報錯誤:

cannot bind non-const lvalue reference of type 'std::__cxx11::string&

而如果構造函數中的string添加了const,就不會報錯了。

2.解答

https://stackoverflow.com/questions/18565167/non-const-lvalue-references,講的很明白

因為一個臨時變量不能綁定到非const引用上。上面的例子中“123”就創建了一個臨時string變量。

但是這個也和編譯器的版本有關,在VS中由於默認啟用了編譯器擴展,因此它可以正常工作。但是在GCC中會報錯。

 

https://blog.csdn.net/lisemi/article/details/103928596,這個說明了為什么臨時變量不能綁定到非const引用上

https://www.cnblogs.com/area-h-p/p/11498481.html

如果一個參數是以非const引用傳入,c++編譯器就有理由認為程序員會在函數中修改這個值,並且這個被修改的引用在函數返回后要發揮作用。但如果你把一個臨時變量當作非const引用參數傳進來,由於臨時變量的特殊性,程序員並不能操作臨時變量,而且臨時變量隨時可能被釋放掉,所以,一般說來,修改一個臨時變量是毫無意義的,據此,c++編譯器加入了臨時變量不能作為非const引用的這個語義限制。

3.例子

std::string a[10]={
        "hello",
        "world",
        "shenzhen"
};
void print(std::string& str){
        std::cout << str << std::endl;
}
std::string get_string(int i){
        return a[i];
}
int main(){
        print(get_string(1));
        return 0;
}

會報錯 error: cannot bind non-const lvalue reference of type

因為get_string返回的是一個臨時變量,可以解決的辦法:

1.print參數加上cosnt

2.print參數去掉&

3.get_string返回一個變量進行定義,再傳入print中


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM