[英]c++ redefine variable as constant
我有一個結構:
struct s { UINT_PTR B_ID; }; s d; d.B_ID=0x1;
效果很好,但我希望d.B_ID保持不變。 我嘗試使用(const),但是沒有用。 因此,在將值添加到d.B_ID之后,我想使其成為常數。
有任何想法嗎?
好吧,我不希望整個結構保持不變。
當我設置計時器並使用b.B_ID作為計時器的提示時。
在switch(wparam){case b.B_ID //錯誤:B_ID必須是常量.... break; 所以這就是為什么我需要它成為一個常量
變量修飾符在編譯時固定為每個變量。 您可能需要解釋您要嘗試做的事情的上下文,但這也許可以滿足您的需求?
struct s
{
int* const B_ID;
};
int main (void) {
int n = 5;
s d = {&n};
int* value = d.B_ID; // ok
// d.B_ID = &n; // error
return 0;
}
由於您使用的是C ++,因此我建議:
class s {
public:
int* const B_ID;
s (int* id) :
B_ID (id) {
}
};
void main (void) {
int n = 5;
s my_s_variable = s(&n);
int* value = my_s_variable.B_ID; // ok
//my_s_variable.B_ID = &n; // error
return 0;
}
Ramiz Toma
: 嗯,我需要使用s.B_ID = something的方法
在C / C ++中,類型修飾符(如const)在運行時聲明給定類型,並且不能在運行時更改。 這意味着,如果將變量聲明為const
,則永遠不能使用賦值運算符將其賦值給該變量。 僅在構造時為其分配一個值。
但這不是問題,因為您始終可以通過適當的設計來解決此問題。
如果您說需要使用賦值,我認為這是因為您在知道變量的值之前先創建了結構。 如果是這種情況,那么您只需要將struct聲明移動到知道該值為止。
例如
s d; //variable declaration
//calculate B_ID
//...
int* n = 5;
//...
d.B_ID = &n;
這將不起作用,因為如果您希望b.D_ID是“不可分配的”,那就總是這樣。 您將需要按照以下方式重構代碼:
//calculate B_ID
//...
int* n = 5;
//...
s d (&n);
//good
struct s
{
s() : B_ID(0){}
UINT_PTR const B_ID;
};
int main(){
s d;
d.B_ID=0x1; // error
}
編輯:對不起,這是C ++中的更新代碼段
struct s
{
s(UINT_PTR const &val) : B_ID(val){}
UINT_PTR const B_ID;
};
int main(){
s d(1);
d.B_ID=0x1; // error
}
在C ++語言中, case
標簽必須從整數常量表達式(ICE)構建。 ICE是編譯器在錯誤消息中的術語“常量”下所暗示的含義。 類的非靜態成員不能在ICE中使用。 從字面上看,您不可能做自己想做的事情。 即,不可能在case
標簽中使用struct成員。
在這種情況case
,無需再考慮switch
/ case
。 if
分支而不是switch
語句,請使用普通的。
你不能那樣做-即。 無法選擇性地使struct const成為單個成員。 一種選擇是“構造”整個結構:
s d;
d.B_ID=0x1;
const s cs = s; // when using this B_ID won't be modifiable - but nor would any other members
或者您可以在構造時設置它:
struct s
{
s(UINT_PTR const p): B_ID(p) {}
UINT_PTR const B_ID;
};
s d(0xabcdef);
另一種方式是獲取和一次性設置
class s
{
private:
bool m_initialized;
UINT_PTR m_value;
public:
s() : m_initialized(false), m_value(NULL) {}
s(UINT_PTR value) : m_initialized(true), m_value(value) {}
//no need for copy / assignment operators - the default works
inline UINT_PTR GetValue() const { return m_value; } //getter
bool SetValue(UINT_PTR value) //works only one time
{
if (m_initialized)
{
m_value = value;
m_initialized=true;
return true;
}
else
{
return false;
}
}
inline bool IsInitialized() const { return m_initialized; }
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.