cartographer运行没有map_map和构造函数的问题

7108f20dbe9a8f625ae565aaf8d4bd1f.png

今天写了一个简单的小程序:

#include <iostream>
#include <map>
#include <string>
using namespace std;

class student
{
    public:
        string name;
        int age;

        student(string n, int a)
        {   
            this->name = n;
            this->age = a;  
        }                                                          
};


int main()
{
    map<int, student> mp; 
    mp[1] = student("jack", 25);
    mp[2] = student("kate", 25);
        
    cout << mp[1].name << endl;

    return 0;  
}

看起来没有问题,但是运行时报错:

test.cpp:23:6:   required from here
/usr/include/c++/4.8.2/bits/stl_map.h:469:59: 错误:对‘student::student()’的调用没有匹配的函数
           __i = insert(__i, value_type(__k, mapped_type()));
                                                           ^
/usr/include/c++/4.8.2/bits/stl_map.h:469:59: 附注:备选是:
test.cpp:12:3: 附注:student::student(std::string, int)
   student(string n, int a)
   ^
test.cpp:12:3: 附注: 备选需要 2 实参,但提供了 0 个
test.cpp:6:7: 附注:student::student(const student&)
 class student
       ^
test.cpp:6:7: 附注: 备选需要 1 实参,但提供了 0 个

问了一下同事 aiden,发现问题在于map在编译阶段发现mp[1]所对应的value不存在,会调用默认构造函数构造一个student对象,可是class student已经写了构造函数,编译器不会生成默认构造函数,所以报错显示:对‘student::student()’的调用没有匹配的函数。

解决方案:添加默认构造函数

class student
{
    public:
        string name;
        int age;

        student(string n, int a)
        {   
            this->name = n;
            this->age = a;  
        }   

        student(){}   
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值