在下文中,我想用智能指標替換“new”的使用。然而,到目前為止,我的嘗試并沒有成功。注釋行是我試圖為智能指標更改的內容。
int main(){
int n, val;
cin>>n;
Person* per[n];
// shared_ptr<Person> per[n];
for(int i = 0;i < n;i ){
cin>>val;
if(val == 1){
per[i] = new Professor;//shared_ptr<Professor>();
}
else {
per[i] = new Student;//shared_ptr<Student>();
}
per[i]->getdata();
}
for(int i=0;i<n;i )
per[i]->putdata();
return 0;
}
定義類的其余代碼如下:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <memory>
using namespace std;
class Person {
public:
int age;
std::string name;
int cur_id_this;
virtual void getdata() {};
virtual void putdata() {};
~Person(){};
};
class Professor : public Person {
public:
int publications;
static int cur_id;
Professor(){
cout << "init prof " << cur_id << endl;
cur_id = 1;
};
void getdata(){
cin >> name >> age >> publications;
cur_id = 1;
cur_id_this = cur_id;
}
void putdata(){
printf("%s %i %i %i\n", name.c_str(), age, publications, cur_id_this);
}
};
class Student : public Person {
public:
std::vector<int> marks;
static int cur_id;
int cur_id_this;
int marks_sum;
void getdata(){
cin >> name >> age;// >> publications;
int grade;
for (auto i=0; i<6; i){
cin >> grade;
marks_sum = grade;
}
std::cout << "---" << marks_sum<< endl;
cur_id = 1;
cur_id_this = cur_id;
}
void putdata(){
printf("%s %i %i %i\n", name.c_str(), age, marks_sum, cur_id_this);
}
};
int Professor::cur_id = 0;
int Student::cur_id = 0;
上面的代碼在命令列中的輸入是:
4
1
Walter 56 99
2
Jesse 18 50 48 97 76 34 98
2
Pinkman 22 10 12 0 18 45 50
1
White 58 87
uj5u.com熱心網友回復:
您沒有分配實際物件,因此請使用std::make_shared:
per[i] = std::make_shared<Student>();
雖然make_shared 是首選,但您可以撰寫:
per[i] = shared_ptr<Professor>(new Professor);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/470082.html
上一篇:如何從SceneDelegate模態呈現ViewController?
下一篇:將位元組大小轉換為無符號整數型別