1. 程式人生 > 其它 >C++關於map自定義鍵值對所出現的問題

C++關於map自定義鍵值對所出現的問題

技術標籤:c++學習c++容器c語言

自定義value提示缺乏預設建構函式
錯誤程式碼:

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

class node {
public:
	int x;
	node(int x) {
		this->x = x;
	}

};
int main() {
	map<int, node> my;
	node s(0);
	my.insert(pair<
int, node>(1, s)); cout << my[1].x; }

報錯提示沒有合適的預設建構函式
報錯資訊

解決方法:在類構造中新增一個空參空描述的建構函式:

class node {
public:
	int x;
	node() {}
	node(int x) {
		this->x = x;
	}

};

因為map要引用此無參預設建構函式,但由於我們已經申明瞭建構函式,所以編譯器無法自己生成一個預設建構函式,此時我們加上一個無參無描述的建構函式來給map呼叫就可以啦!

output

0