Given 2 klas:Jak mogę uzyskać błąd kompilacji przy przypadkowej konstrukcji?
...
class Grades{
public:
Grades(int numExams) : _numExams(numExams){
_grdArr = new double[numExams];
}
double GetAverage() const;
...
private: // The only data members of the class
int _numExams;
double *_grdArr;
};
class Student{
public:
Student(Grades g) : _g(g){
}
...
private: // The only data members of the class
Grades _g;
};
...
, a krótki program główny:
int main(){
int n = 5; // number of students
Grades g(3); // Initial grade for all students
// ... Initialization of g – assume that it's correct
Student **s = new Student*[n]; // Assume allocation succeeded
for (int it = 0 ; it < n ; ++it){
Grades tempG = g;
// ... Some modification of tempG – assume that it's correct
s[it] = new Student(tempG);
}
// ...
return 0;
}
Ten kod działa poprawnie. Ale przez typo pomyłkę wiersza:
Grades tempG = g;
zmienił się:
Grades tempG = n;
i nadal przechodzi kompilację. Jaką prostą zmianę mogę zrobić w kodzie (głównym() kodzie), aby uzyskać błąd kompilacji przez ten błąd literówki?
Nie ma potrzeby używania "nowego" w tym kontekście. Powinieneś raczej preferować zmienne stosowe (zmienne automatyczne lub stałe), a nie sterty (zmienne dynamiczne). Wyszukaj std :: vector. –