在此示例中用智能指针替换 new

replacing new with smart pointers in this example

在下文中,我想用智能指针替换“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

你没有分配实际的对象,所以使用 std::make_shared :

per[i] = std::make_shared<Student>();

虽然make_shared is preferred,你可以这样写:

per[i] = shared_ptr<Professor>(new Professor);