繁体   English   中英

防止对象切片-C ++

[英]Preventing Object Slicing - C++

我正在尝试创建Person对象的向量。 但是我真的想存储从Person基类派生的Adult,Professor和Student对象。 问了这个问题之后,我知道我的问题出在对象拼接中,它将派生类保存为Person类,因为这就是向量的含义。 我试图修改代码以纠正这种情况,但是我仍然遇到一些错误,需要一些其他帮助。 谢谢!

这是我的main.cpp代码:

#include "Person.h"
#include "Professor.h"
#include "Student.h"
#include "Adult.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;

template<typename T> void addPerson(vector<Person *> &personVector) {
    cout << "DEBUG" << endl;
    personVector.push_back(new T());
}

void addFriend(vector<Person *> &personVector) {
    bool loop = true;
    while (loop) {
        cout << "\nWhich Person would you like to create? " << endl;
        cout << "  1. Professor" << endl;
        cout << "  2. Student" << endl;
        cout << "  3. Adult" << endl;
        int caseVar;
        cin >> caseVar;
        switch (caseVar) {
        case 1: 
            addPerson<Professor>(personVector);
            // old incorrect line: addPerson<Professor *>(personVector);
            loop = false;
            break;
        case 2: 
            addPerson<Student>(personVector);
            // old incorrect line: addPerson<Student *>(personVector);
            loop = false;
            break;
        case 3: 
            addPerson<Adult>(personVector); 
            // old incorrect line: addPerson<Adult *>(personVector);
            loop = false;
            break;
        default: cout << "Unknown Entry Please Try Again." << endl;
        }
    }
}

void displayFriends(vector<Person *> &personVector) {
    if (personVector.size() > 1) {
        for (unsigned i = 0; personVector.size() > i; i++)
            cout << i+1 << ". " << personVector[i]->getName() << endl;
            cout << "DEBUG" << endl;
    }
}

void viewFriend(vector<Person *> &personVector) {
    if (personVector.size() > 1) {
        displayFriends(personVector);
        cout << "Which # friend would you like to view? ";
        int num;
        cin >> num;
        personVector[num-1]->coutPerson();
    } else if (personVector.size() == 1) {
        personVector[0]->coutPerson();
    } else {
        cout << "No friends to View." << endl;
    }
}


void deleteElementFromArray(int element, vector<Person *> &personVector) {
    vector<Person *> newPersonVector;
    for (unsigned i = 0; personVector.size() > i; i++)
        if (i != element - 1)
            newPersonVector.push_back(personVector[i]);
    personVector = newPersonVector;
}

void removeFriend(vector<Person *> &personVector) {
    if (personVector.size() > 1) {
        displayFriends(personVector);
        cout << "Which # friend would you like to remove? ";
        unsigned num;
        cin >> num;
        if (num <= personVector.size())
            deleteElementFromArray(num, personVector);
        else
            cout << "Invalid Selection" << endl;
    } else if (personVector.size() == 1) {
        cout << "Removed one and only friend" << endl;
    } else {
        cout << "No friends to Remove." << endl;
    }
}


int main() {
    vector<Person *> personVector;
    // Run Main Menu
    cout << "Friends with Stuff" << endl;
    cout << "Adding 5 friends to the list" << endl;
    personVector.push_back(new Person("James"));
    personVector.push_back(new Person("Martin"));
    personVector.push_back(new Person("Sammi"));
    personVector.push_back(new Person("Donny"));
    personVector.push_back(new Person("Ronald"));
    bool loop = true;
    while (loop) {
        cout << "\nWhat would you like to do? " << endl;
        cout << "  1. Add New Friend" << endl;
        cout << "  2. View Friend" << endl;
        cout << "  3. Remove Friend" << endl;
        cout << "  4. Clear Friends" << endl;
        cout << "  5. Get Object" << endl;
        cout << "  6. Exit" << endl;
        int caseVar;
        cin >> caseVar;
        switch (caseVar) {
        case 1: 
            addFriend(personVector);
            break;
        case 2: 
            viewFriend(personVector);
            break;
        case 3: 
            removeFriend(personVector);
            break;
        case 4: 
            personVector.clear();
            break;
        case 5:

            break;
        case 6: 
            loop = false; 
            break;
        default: cout << "Unknown Entry Please Try Again." << endl;
        }
    }
}

我收到以下错误

InitializeBuildStatus:
1>  Touching "Debug\FPVisualStudio.unsuccessfulbuild".
1>ClCompile:
1>  main.cpp
1>\\cs1\cs_students\mlindahl15\cs172\final project\fpvisualstudio\main.cpp(12): error C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'Professor **' to 'Person *&&'
1>          with
1>          [
1>              _Ty=Person *
1>          ]
1>          Reason: cannot convert from 'Professor **' to 'Person *'
1>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>          \\cs1\cs_students\mlindahl15\cs172\final project\fpvisualstudio\main.cpp(26) : see reference to function template instantiation 'void addPerson<Professor*>(std::vector<_Ty>)' being compiled
1>          with
1>          [
1>              _Ty=Person *
1>          ]
1>\\cs1\cs_students\mlindahl15\cs172\final project\fpvisualstudio\main.cpp(12): error C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'Student **' to 'Person *&&'
1>          with
1>          [
1>              _Ty=Person *
1>          ]
1>          Reason: cannot convert from 'Student **' to 'Person *'
1>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>          \\cs1\cs_students\mlindahl15\cs172\final project\fpvisualstudio\main.cpp(30) : see reference to function template instantiation 'void addPerson<Student*>(std::vector<_Ty>)' being compiled
1>          with
1>          [
1>              _Ty=Person *
1>          ]
1>\\cs1\cs_students\mlindahl15\cs172\final project\fpvisualstudio\main.cpp(12): error C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'Adult **' to 'Person *&&'
1>          with
1>          [
1>              _Ty=Person *
1>          ]
1>          Reason: cannot convert from 'Adult **' to 'Person *'
1>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>          \\cs1\cs_students\mlindahl15\cs172\final project\fpvisualstudio\main.cpp(34) : see reference to function template instantiation 'void addPerson<Adult*>(std::vector<_Ty>)' being compiled
1>          with
1>          [
1>              _Ty=Person *
1>          ]
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.90
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我相信这是在告诉我我的代码中有太多的指针。 但是我不明白为什么会这样。 我仅有的指针是说向量包含在每种情况下都需要重复的地方。 而且这些指针是必需的,因此我没有对象切片。

Person.h

#ifndef PERSON_H
#define PERSON_H
#include <string>
#include "Date.h"
#include "PhoneNumber.h"
using namespace std;

class Person
{
protected:
    string name;
    Date birthday;
    PhoneNumber phoneNumber;
    string city, state;
public:
    // Constructors
    Person();
    Person(string name) { 
        this->name = name; 
        birthday = Date();
        phoneNumber = PhoneNumber("0000000000");
        city = "Unknown";
        state = "Unknown";
    }
    // Getter and Setter Methods
    string getName();
    void setName(string);
    Date getBirthday();
    // Methods
    void coutPerson();
};
#endif

Person.cpp

#include "Person.h"
#include "PhoneNumber.h"
#include "Date.h"
#include <string>
#include <iostream>
using namespace std;

// Constructors
Person::Person() {
    cin.ignore();
    cout << "Name? ";
    getline(cin, name);
    cout << "Birthday: " << endl;
    birthday.askUserForDate();
    phoneNumber.create();
    cout << "City? ";
    getline(cin, city);
    cout << "State? ";
    getline(cin, state);
}

// Getter and Setter Methods
string Person::getName() {
    return name;
}

void Person::setName(string name) {
    this->name = name;
}

void Person::coutPerson() {
    cout << name << endl;
    birthday.coutDate();
    phoneNumber.coutPhoneNumber();
    cout << city << ", " << state << endl;
}

// Methods

Student.h

#ifndef STUDENT_H
#define STUDENT_H
#include "Person.h"
using namespace std;

class Student : public Person
{
private:
    string dorm;
    int dormRoom;
public:
    // Constructors
    Student();
    Student(Student &);
    // Getter and Setter Methods

    // Methods
    void coutPerson();
};
#endif

Student.cpp

#include "Student.h"
#include "Person.h"
#include <string>
#include <iostream>
using namespace std;

// Constructors
Student::Student() {
    cin.ignore();
    cout << "Dorm? ";
    getline(cin, dorm);
    cout << "Dorm Room #? ";
    cin >> dormRoom;
}

// TODO Copy Constructors
// TODO Deconstructors
// Overload < > ==

Student::Student(Student &student) {
    Person::Person(student);
    dorm = student.dorm;
    dormRoom = student.dormRoom;
}

void Student::coutPerson() {
    cout << "DEBUG: Student::coutPerson()" << endl;
    Person::coutPerson();
    cout << "Dorm Room: " << this->dorm << " " << this->dormRoom << endl;
}

// Methods

您需要删除模板参数中的*

例如:

addPerson<Professor *>(personVector);

替换为:

addPerson<Professor>(personVector);

目前,您正在创建Professor **


更新:并且在您的main() ,您应该使用new Person("Name")创建人员,您现在使用的 是没有意义的,即“采用这种地址” 可行的 ,但可以一个非常坏的主意(获取在堆栈上创建的对象的地址)。

例如:

personVector.push_back(&Person("James"));

替换为:

personVector.push_back(new Person("James"));

Update2:请注意,您有责任在某个时候释放以这种方式分配的内存。

您的模板参数是指针,但不应该这样,因为在您的方法中,例如template<typename T> void addPerson(...)您将使用new创建一个新的T实例,从而创建一个指向人(即new Person*()的新指针。 new Person*()将导致一个Person*** )。

因此,可以这样称呼它: addPerson<Professor>(personVector); 这会将new T()转换为new Professor() ,从而产生Professor*结果。

另一件事:

void deleteElementFromArray(int element, vector<Person *> personVector) {
  vector<Person *> newPersonVector;
  for (unsigned i = 0; personVector.size() > i; i++)
    if (i != element - 1)
        newPersonVector.push_back(personVector[i]);
    personVector = newPersonVector;
}

首先,您要删除element - 1因此请注意您不能传递0(即, element在此处是基于一个的索引)。

其次,将newPersonVector分配给参数personVector 但是,由于您要按值传递矢量(将其复制),因此在该函数外部将看不到更改。

您有几种解决方案:

  1. personVector删除该项目,而不是复制不应删除的项目。 personVector.erase(personVector.begin() + element)使用诸如personVector.erase(personVector.begin() + element)类的东西(请注意,这里的语法可能不太正确,但您应该得到它)。
  2. 传递指向向量的指针: void deleteElementFromArray(int element, vector<Person *>* personVector)
  3. 返回新向量并替换旧向量。 因此,该调用变为personVector = removeFriend(personVector);

我个人更喜欢选项1,因为它可以重用向量,从而减少了复制操作。

编码

addPerson<Professor *>(personVector); 

尝试修改为:

addPerson<Professor>(personVector); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM