[英]Error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
[英]error: cannot initialize a variable of type 'int *const' with an rvalue of type 'const int *
為什么我會收到此錯誤: error: cannot initialize a variable of type 'int *const' with an rvalue of type 'const int *
? 代碼:
constexpr int ch1 = 5;
constexpr int* pch1 = &ch1;
constexpr int ch2 = 5;
constexpr int* pch2 = &ch2;
cout << *pch1+*pch2;
讓我說清楚。 這整個考驗的重點是在編譯時初始化這些變量。 如果有更好的方法可以做到這一點,請告訴我。
您已將pch1
和pch2
聲明為constexpr
的事實本身並不會使它們成為const int *
,因此您需要:
constexpr int ch1 = 5;
constexpr const int* pch1 = &ch1;
constexpr int ch2 = 5;
constexpr const int* pch2 = &ch2;
但是,你會得到:
error: '& ch1' is not a constant expression
error: '& ch2' is not a constant expression
所以你還是沒有贏。
編輯:正如克里斯指出的那樣,您可以通過將ch1
和ch2
聲明為static
來解決后一個問題。 他們的地址然后變成constexpr
:
constexpr static int ch1 = 5;
constexpr const int* pch1 = &ch1;
constexpr static int ch2 = 5;
constexpr const int* pch2 = &ch2;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.