提问者:小点点

关于vector-push_back和返回指针


我有一个问题与Schoot::AddStudent(。。。)有关

这是来自班级学校的编码。

    class School {

        string schoolName ;
        vector<Student> students;
    public:
        School(const string& _schoolName) : schoolName(_schoolName) {}
        Student* addStudent(const string& name, MajorType majorType) {
        students.push_back(Student(name, 0, majorType));
        return &students[students.size()-1];
        }
    Student* addStudent(const string& name, const float gpa) {
        students.push_back(Student(name, gpa, UD));
        return &students[students.size()-1];
        }
    ...
    }

这是来自班级学生编码

    class Student {
        string name;
        float gpa;
        Major major;
    public:
        Student() : name("null"), major(UD) {
            this->gpa=0;
        }
        Student(const string& _name, const float _gpa, const Major _major) 
                : name(_name), major(_major) {
                gpa = _gpa;
            }
        void set(const string& _name, MajorType _majorType) {
            name = _name;
            this->gpa=0;
            major.setMajor(_majorType);
        }
        void set(const string& _name, const float gpa) {
            name = _name;
            this->gpa = gpa;
            major.setMajor(UD);
        }
        void setName(const string& _name) {
            name = _name;
        }
        void setGPA(const float gpa) {
            this->gpa = gpa;
        }
        void setMajor(const MajorType majorType) {
            major.setMajor(majorType);
        }
    } ;

我是班长。

    class Major { 
        MajorType majorType ;
    public:
        Major(const MajorType _majorType) : majorType(_majorType) {}
    
        MajorType getmajorType() const {
            return majorType;
        }
        void setMajor(const MajorType _majorType) {
            majorType=_majorType;
        }
    };

这是一个简单的枚举。想跳就跳。

    enum MajorType {CE, EE, ME, UD};

问题来了。当我用这种方式编写student*addstudent时,它工作得很好。

但当我编码student*addstudent

        Student* addStudent(const string& name, MajorType majorType) {
            Student* tmp = new Student();
            tmp->set(name, majorType);
            students.push_back(*tmp);
            return tmp;
        }
        Student* addStudent(const string& name, const float gpa) {
            Student* tmp = new Student();
            tmp->set(name, gpa);
            students.push_back(*tmp);
            return tmp;
        }

null

对于那些想知道后一种代码的结果的人

校名:PNU,人数:4名:Kim,GPA:0,专业:电气工程。姓名:Hong GPA:0专业:计算机工程。姓名:李GPA:4专业:待定。姓名:Joo GPA:1.5专业:待定。

主代码中有输入Kim和Hong的GPA以及Lee和Joo的专业的位元,但代码就是不起作用

null


共1个答案

匿名用户

如果您的编译器支持Cpp11,请替换

 vector<Student> students;

 vector<std::shared_ptr<Student>> students;

并使用共享指针。

请参阅共享指针文档

这也应该可以缓解当前代码中的内存泄漏问题。

Student* addStudent(const string& name, const float gpa) {
    Student* tmp = new Student();
    tmp->set(name, gpa);
    students.push_back(*tmp);
    return tmp;
}