簡體   English   中英

簡單的C ++聲明問題

[英]Simple C++ Declaration Issue

為什么這是非法的,還有什么合理的選擇?

// State.h
class State {

public:
int a;
int b;
State z; //  <-- this is this problem

// ... Functions ...

};

謝謝。

因為,如果允許的話,每次創建一個State實例時,您都會創建一個State實例,然后再創建一個State實例,而且,那個實例也需要一個State ,所以它也會創建State實例。 。 等等。

當試圖找出sizeof(State)它還會使您的編譯器進行無限遞歸。 對您的編譯器好。

而是改用一種指針,這樣就可以了。 附帶說明一下,一個State擁有自己的(公共) State真的有意義嗎? 我的意思是,我確實喜歡看到如下代碼行,但這可能會變得荒謬……

if(state.z->z->z->z->z->z->z->z == some_state) {
    // we found the right state!
}

如果您嘗試創建單例,請將構造函數get_instance私有,並添加一個靜態的get_instance函數,該函數返回State唯一(靜態)實例。

由於z是局部變量,因此在掃描整個State類之前,您不知道需要多少存儲空間。 由於State取決於自己,因此您將無限遞歸。

基本上,這就是編譯器中發生的事情:

I see a class state.  Okay!
I now see a member variable a.  Okay!  Let's add 4 bytes to the size of our state
I now see a member variable b.  Okay!  Let's add 4 bytes to the size of our state
I now see a State.  Okay!  Let's see, our current size is 4 + 4, 
    now let's add the size of State to that, which is... um... ????

另一方面,指針在編譯時具有已知的大小(通常為4個字節,但這取決於您的體系結構。)這樣,當您不知道某事物的大小時,您總可以擁有一個指向它的指針,因為該大小並不重要。

這是編譯器在此時發生的情況:

I see a class state.  Okay!
I now see a member variable a.  Okay!  Let's add 4 bytes to the size of our state
I now see a member variable b.  Okay!  Let's add 4 bytes to the size of our state
I now see a State*.  Okay!   Let's add 4 bytes to the size of our state
I now see that class state has ended.  Its size is 4 + 4 + 4 = 12.
I can now do State z;  It will take 12 bytes of space.

不合邏輯的,因為這會狀態Z的無限數量的結束,因為z的所有實例都將有z與另一個實例中,並依此類推。 指針狀態* z被允許,因為它沒有這樣的限制

請改用State * 這樣一來,您就可以結束遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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