我一直在嘗試將一組物件傳遞給另一個類物件。
在settingUp.cpp:
//** Status classes and their functions **//
void settingUp(){
dataClass prueba0;
dataClass prueba1;
dataClass prueba2;
const dataClass * arrayPrueba[3];
prueba0.setValues(1);
prueba1.setValues(2);
prueba2.setValues(3);
arrayPrueba[0] = &prueba0;
arrayPrueba[1] = &prueba1;
arrayPrueba[2] = &prueba2;
statusClass status;
status.setValues(1, arrayPrueba);
status.printValues();
}
在classData.cpp:
//** dataClass and their functions **//
void dataClass::setValues(int _length){
length = _length;
}
void dataClass::printValues() const{
printf("TP: dataClass: length = %d\n", &length);
};
在statusClass.cpp:
//** Status classes and their functions **//
void statusClass::setValues (uint8_t _statusSelectorByte, const dataClass **_array){
newStatusSelectorByte = _statusSelectorByte;
array = *_array;
};
void statusClass::printValues(){
printf("TP: statusClass -> printValues: Prueba = %d\n", newStatusSelectorByte);
printf("TP: statusClass -> printValues: arrayPrueba = %d\n", array[1].length);
}
當我打電話時:
status.printValues();
我只能讀取arrayPrueba.
uj5u.com熱心網友回復:
在中statusClass::setValues(),*_array與 相同_array[0]。您只存盤dataClass*輸入陣列中的第一個指標。
后來,當使用 時array[1],您會誤 array認為它是指向物件陣列的指標,而實際上它是指向單個物件的指標。因此,您正在通過該物件進入周圍的記憶體,這是未定義的行為(但在這種情況下可能“起作用”,因為物件可能碰巧實際存在于該位置,但這是依賴的不良行為)。
您需要存盤原始陣列指標,而不是從陣列中取出的單個元素。
private:
const dataClass **array; // <-- add an *
void statusClass::setValues (uint8_t _statusSelectorByte, const dataClass **_array){
newStatusSelectorByte = _statusSelectorByte;
array = _array; // <-- get rid of the *
};
void statusClass::printValues(){
printf("TP: statusClass -> printValues: Prueba = %d\n", newStatusSelectorByte);
printf("TP: statusClass -> printValues: arrayPrueba = %d\n", array[1]->length); // use -> instead of .
}
附帶說明:在 中dataClass::printValues(),您需要&在列印 的值時洗掉length:
printf("TP: dataClass: length = %d\n", length);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/528746.html
標籤:C 数组班级目的
