2013-10-24 33 views
7

我定義了一個私有變量:如何使用const_cast?

const int studentNumnber; 

我試圖寫一個拷貝構造函數,我需要拋棄常量性要做到這一點,可惜我不知道如何用const_cast。

這就是我想在我的拷貝構造函數做的:

Student(const Student & s) 
     : Person(p.getName(), p.getEmailAddress(), p.getBirthDate()), school(0),  studentNumber(0){ 
     school = new char[strlen(s.school) +1]; 
     strcpy_s(school, strlen(s.school) +1, s.school); 
     const_cast<int*>(this)->studentNumber = s.studentNumber; 
      //studentNumber= s.studentNumber); 
    } 

這不工作...我不能確定的語法是這樣做

+0

這是瘋了。什麼是'e'?你應該在初始化列表中有'studentNumber(s.StudentNumber)';或者說,不要自己寫一個拷貝構造函數。 –

回答

30

你是不是有什麼允許到const_cast變量實際上是const。這導致未定義的行爲。 const_cast用於從引用和指針中移除常量,最終引用的內容不是const

所以,這是允許的:

int i = 0; 
const int& ref = i; 
const int* ptr = &i; 

const_cast<int&>(ref) = 3; 
*const_cast<int*>(ptr) = 3; 

它是允許的,因爲i,該對象被分配到,是不是const。以下是不允許的:

const int i = 0; 
const int& ref = i; 
const int* ptr = &i; 

const_cast<int&>(ref) = 3; 
*const_cast<int*>(ptr) = 3; 

因爲這裏iconst和你被分配一個新的值修改它。該代碼將被編譯,但其行爲是不確定的(這可能意味着任何從「它工作正常」到「程序崩潰」)。

您應該在構造函數的初始化器中初始化常量數據成員,而不是將它們分配給構造函數的主體:

Student(const Student & s) 
    : Person(p.getName(), p.getEmailAddress(), p.getBirthDate()), 
     school(0), 
     studentNumber(s.studentNumber) 
{ 
    // ... 
} 
+0

我明白我不應該這樣做,但不幸的是我不得不使用const_cast,因爲這是如何設置這個任務的。我只是不明白代碼的語法。我知道這是這樣的:const_cast < new_type >(表達式)\t \t但我不明白。 – Sarah

+2

@Sarah,然後你的任務迫使你調用未定義的行爲,如果結果不同,你的教授不應該感到驚訝。這是假設它首先編譯。 – chris

+0

@Sarah附加了const_cast的用法。 – timrau

-1

在你的代碼中你試圖使用這個指針而不是變量。您可以嘗試以下操作:

Student(const Student & s) 
    : Person(p.getName(), p.getEmailAddress(), p.getBirthDate()), school(0),  studentNumber(0){ 
    school = new char[strlen(s.school) +1]; 
    strcpy_s(school, strlen(s.school) +1, s.school); 
    ***const_cast<int*>(&studentNumber) = s.studentNumber;**    
}