簡體   English   中英

錯誤:無法使用“const int *”類型的右值初始化“int *const”類型的變量

[英]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;

讓我說清楚。 這整個考驗的重點是在編譯時初始化這些變量。 如果有更好的方法可以做到這一點,請告訴我。

您已將pch1pch2聲明為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

所以你還是沒有贏。

現場演示


編輯:正如克里斯指出的那樣,您可以通過將ch1ch2聲明為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM