读书人

map中结构体的赋值解决思路

发布时间: 2012-03-25 20:55:17 作者: rapoo

map中结构体的赋值

C/C++ code
/************************************************************************//* pair对象的创建和使用                                                                     *//************************************************************************/#include <iostream>#include <utility>#include <map>#include <string.h>using namespace std;class Student {public:    Student()    {        strcpy(m_sName, "NULL");        m_nAge = 0;    }    Student(char sName[20], int nAge)    {        strcpy(m_sName ,sName);        m_nAge = nAge;    }    Student(Student& s1)    {        strcpy(m_sName, s1.GetName());        m_nAge = s1.GetAge();    }    int GetAge()    {        return m_nAge;    }    char * GetName()    {        return m_sName;    }private:    char            m_sName[20];    unsigned int    m_nAge;    };int main(){    Student s1("sdd",3);    map<int, Student> m1;    m1.insert(pair<int, Student>(12, s1) );        return 0;}


怎么传结构体啊? 怎么改啊?

[解决办法]
map<int, Student> m1;
m1.insert(pair<int, Student>(12, Student("sdd",3)) );
m1[13] = Student("scc", 4);
[解决办法]
错误描述 error: Student 没有可用的复制构造函数或复制构造函数声明为“explicit”

容器元素类型有两个最基本的约束:
元素类型必须支持赋值运算
元素类型的对象必须可以复制

给 Student定义复制构造函数吧 因为容器内部的元素是通过复制初始化的~~
[解决办法]
缺了拷贝构造,你那个没const的不行
Student(const Student& s1)

[解决办法]
2010 通过



insert成员函数不就可以了吗


[解决办法]
C/C++ code
class Student {public:    Student()    {        strcpy(m_sName, "NULL");        m_nAge = 0;    }    Student(int a)    {        m_nAge = a;    }    Student(const char*sName, int nAge)    {        strcpy(m_sName ,sName);        m_nAge = nAge;    }    Student(const Student& s1)    {        strcpy(m_sName, s1.m_sName);        m_nAge = s1.m_nAge;    }    int GetAge()    {        return m_nAge;    }    char * GetName()     {        return m_sName;    }private:    char            m_sName[20];    unsigned int    m_nAge;    };int main(){   // Student s1;    map<int, Student> m1;    m1.insert(pair<int,Student>(12, Student("lilin", 3)) );    system("pause");    return 0;}
[解决办法]
返回值类型改成 const char*就是了

读书人网 >C++

热点推荐