2012-03-19 47 views
1

我已經此構造節點類:如何一個常量指針傳遞給方法的類

Node::Node(int item, Node const * next) 
{ 
    this->item = item; 
    this->next = next; 
} 

當我編譯它給出了一個編譯錯誤:從「常量節點*」無效轉換'Node *'

有沒有辦法傳遞指向常量數據的指針?

回答

5

你做正確,但是編譯器是正確的抱怨:你分配一個「指針常量Node」給一個變量,類型爲「指向一個非const Node」的。如果以後修改this->next,你違反了「我不會修改變量指向next

最簡單的解決方法是剛剛宣佈next爲指針,以非const數據。如果變量this->next合同將真正永遠不會被修改爲Node對象的生活,那麼你還可以聲明類的成員是一個指向const對象:

class Node 
{ 
    ... 
    const Node *next; 
}: 

還要注意區分「指針const數據」和「 const數據指針「。對於單級普安特RS,有4種類型的問候指針他們const岬:

Node *ptr; // Non-constant pointer to non-constant data 
Node *const ptr; // Constant pointer to non-constant data 
const Node *ptr; // Non-constant pointer to constant data 
Node const *ptr; // Same as above 
const Node *const ptr; // Constant pointer to constant data 
Node const *const ptr; // Same as above 

注意const Node相同Node const在最後一個級別,但const與問候的指針聲明的位置(「*」 ) 非常重要。

0

Is there a way to pass a pointer pointing to constant data?

是的。如您在代碼中顯示的那樣使用Node const*(或const Node*)。

要解決你的編譯器錯誤,你有3種選擇:

  1. Node::Node()應該接受一個非const指針,以便 它可以被分配到this->next
  2. 更改設計和申報Node::nextNode const*
  3. 類型轉換,this->next = const_cast<Node*>(next);

第三小號應謹慎使用溶液,否則可能導致未定義的行爲。

0
It also works with pointers but one has to be careful where ‘const’ is put as that determines whether the pointer or what it points to is constant. For example, 

    const int * Constant2 
declares that Constant2 is a variable pointer to a constant integer and 

    int const * Constant2 
is an alternative syntax which does the same, whereas 

    int * const Constant3 
declares that Constant3 is constant pointer to a variable integer and 

    int const * const Constant4 
declares that Constant4 is constant pointer to a constant integer. Basically ‘const’ applies to whatever is on its immediate left (other than if there is nothing there in which case it applies to whatever is its immediate right). 

http://duramecho.com/ComputerInformation/WhyHowCppConst.html我認爲這個鏈接將幫助you.you需要知道什麼const mean.Good運氣。

相關問題