注意 - 我有搜索了很多關於C++的指針和引用。 我似乎並不瞭解他們在這個特殊情況。因此張貼在這裏!在這段C++代碼中指針的必要性是什麼?
以下是正確代碼。這是工作。我寫了這個在線C++實踐問題。最初給我一部分代碼。
我不理解爲什麼人對象數組被在主函數創建了一個帶有*每個[n]的,如下所示:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Person {
string name;
int age;
public:
Person(){
name = "";
}
virtual void putdata() = 0;
virtual void getdata() = 0;
};
class Professor: public Person {
int publications, cur_id;
string name;
int age;
public:
static int professorCount;
Professor(){
name = "";
age = 0;
publications = 0;
cur_id = professorCount + 1;
professorCount++;
}
void getdata(){
cin >> name >> age >> publications;
}
void putdata(){
cout << name << " " << age << " " << publications << " " << cur_id << endl;
}
};
class Student: public Person {
int marks[6];
int cur_id;
string name;
int age;
public:
static int studentCount;
Student(){
name = "";
age = 0;
cur_id = studentCount + 1;
studentCount++;
}
void getdata(){
cin >> name >> age >> marks[0] >> marks[1] >> marks[2] >> marks[3] >> marks[4] >> marks[5];
}
void putdata(){
cout << name << " " << age << " " << marks[0] + marks[1] + marks[2] + marks[3] + marks[4] + marks[5] << " " << cur_id << endl;
}
};
int Professor::professorCount = 0;
int Student::studentCount = 0;
在低於該主功能,陣列Person對象正在創建,但它在開始時被賦予*。它是如何工作的?
int main(){
int n, val;
cin>>n; //The number of objects that is going to be created.
Person *per[n]; // THIS ONE RIGHT HERE! THIS ONE!
for(int i = 0;i < n;i++){
cin>>val;
if(val == 1){
// If val is 1 current object is of type Professor
per[i] = new Professor;
}
else per[i] = new Student; // Else the current object is of type Student
per[i]->getdata(); // Get the data from the user.
}
for(int i=0;i<n;i++)
per[i]->putdata(); // Print the required output for each object.
return 0;
}
就這樣可以填充陣列滿或內存泄漏是方式更方便,更不容易出錯。 – juanchopanza
@juanchopanza - 請你詳細說明一下。謝謝! –
標識使用的變量長度數組(VLA)不支持*標準* C++,但某些編譯器添加爲擴展。轉換爲'std :: vector'或使用動態內存分配。 –