在C ++中用CPerson类型的对象初始化STL向量(类)?

时间:2018-10-28 18:55:35

标签: c++ vector stl

我有一个类CPerson,我想用对象变量初始化类型CPerson的向量。但是,编译器会说type name is not allowed。我想问为什么?

class CPerson {
protected:
    string m_strName; 
    Sex m_Sex; 
    Titles m_Title; 
public:
    CPerson() {
        m_strName = "Peter Petrov";
        m_Sex = male;
        m_Title = bachelor;
    }
    //добавяме параметричен к-р
    CPerson(string n,Sex s,Titles t) {
        m_strName = n;
        m_Sex = s;
        m_Title = t;
    }
    ~CPerson() {}
    void SetName(string strName) {
        m_strName = strName;
    }
    void SetSex(Sex sex) {
        m_Sex = sex;
    }
    void SetTitle(Titles title) {
        m_Title = title;
    }
    string GetName() const {
        return m_strName;
    }
};

int main(){
vector <CPerson> perr = { CPerson p1,
    CPerson p2("I.Ivanov", male, professor),
    CPerson p3("A.Stoyanova", female, assistant),
    CPerson  p4("A.Dimitrova", female, assistant)}
    return 0;
} 

1 个答案:

答案 0 :(得分:1)

您的代码中有很多问题。这是可以成功编译的代码版本:

// Example program
#include <iostream>
#include <string>
#include <vector>

enum class Sex {
    male, female
};

enum class Titles {
    bachelor,
    assistant,
    professor
};

class CPerson {
protected:
    std::string m_strName; 
    Sex m_Sex; 
    Titles m_Title; 
public:
    CPerson() {
        m_strName = "Peter Petrov";
        m_Sex = Sex::male;
        m_Title = Titles::bachelor;
    }
    //добавяме параметричен к-р
    CPerson(std::string n,Sex s,Titles t) {
        m_strName = n;
        m_Sex = s;
        m_Title = t;
    }

    void SetName(std::string strName) {
        m_strName = strName;
    }
    void SetSex(Sex sex) {
        m_Sex = sex;
    }
    void SetTitle(Titles title) {
        m_Title = title;
    }
    std::string GetName() const {
        return m_strName;
    }
};

int main(){
    std::vector <CPerson> perr({ 
        CPerson(),
        CPerson("I.Ivanov", Sex::male, Titles::professor),
        CPerson("A.Stoyanova", Sex::female, Titles::assistant),
        CPerson("A.Dimitrova", Sex::female, Titles::assistant)
    });
    return 0;
} 

除了缺少“性别”和“标题”的类型外,主要问题还在于向量初始化程序的语法。我假设您正在尝试使用初始化列表,但是语法完全错误。看起来您只是将变量声明/初始化语句复制到其中,但是您需要创建CPerson类的新实例。然后将这些实例复制到向量中。

CPerson p2("I.Ivanov", male, professor)

在堆栈上声明并初始化类p2的名为CPerson的变量,但是此语法在初始化列表中无效,因为不允许在此声明变量。而是使用

CPerson("I.Ivanov", Sex::male, Titles::professor)

这将创建CPerson的实例,然后将该实例复制到向量中。