- I は、C++のポインタと参照を多く検索しました。 これはわかりません。こののシナリオです。したがってここにそれを掲示する!このC++コードでポインタの必要性は何ですか?
以下は、CORRECTコードです。それは働いている。私はこれをオンラインC++の練習問題のために書いた。最初にコードの一部が私に与えられました。以下に示すように、Personオブジェクトの配列[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 - 詳細を教えてください。ありがとうございました! –
*標準* C++ではサポートされていない可変長配列(VLA)が使用されていますが、一部のコンパイラでは拡張機能として追加されています。 'std :: vector'に変換するか、動的メモリ割り当てを使います。 –