注意 - 我有搜索了很多关于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'或使用动态内存分配。 –