c++ - 构造函数重载造成困惑

标签 c++ dictionary constructor std stdmap

#include<bits/stdc++.h>
#define mpq pair<int,Query>
using namespace std;

class Query{
    public:
    int a1,a2,b1,b2,c1,c2,d,l,r;
    Query(){}
    Query(int a1,int a2,int b1,int b2,int c1,int c2,int d,int l,int r){
        this->a1=a1; this->a2=a2;
        this->b1=b1; this->b2=b2;
        this->c1=c1; this->c2=c2;
        this->d=d; this->l=l; this->r=r;
        print();
    }
    Query(int d,int l,int r){
        Query(0,1,0,1,0,1,d,l,r);
    }

    void print(){
        cout<<d<<" "<<l<<" "<<r<<endl;
    }
};

map<int,Query> query;
int main(){
    query.insert(mpq(1,Query(0,1,0,1,0,1,1,1,1)));
    query[1].print();
    cout<<endl;

    query[4]=Query(4,4,4);//not working properly
    query[4].print();//giving output of query[1].print
    cout<<endl;

    query[2]=Query(0,1,0,1,0,1,2,2,2);
    query[2].print();

}

我无法解释这段代码的输出 query[4].print() 给出了意外的输出

我期望输出是

4 4 4

但它正在给予

1 1 1

作为输出

最佳答案

这里的问题是

Query(int d,int l,int r){
    Query(0,1,0,1,0,1,d,l,r);
}

什么都不做。 Query(0,1,0,1,0,1,d,l,r); 创建一个临时的 Query 然后销毁它。我认为您打算使用委托(delegate)构造函数,这看起来像

Query(int d,int l,int r) : Query(0,1,0,1,0,1,d,l,r) {}

关于c++ - 构造函数重载造成困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116548/

相关文章:

c++ - 无法将字符串文字分配给装箱的 std::string vector

c++ - 绘制 QTableView 的背景(使用自定义 QStyledItemDelegate)

dictionary - 在给定 Kotlin 中的键列表的情况下切片 map

python - 乘以字典中的项目列表

python - 迭代两个或多个列表/numpy 数组...并将每个项目相互比较并避免 python 中的循环

java - 为什么我们使用不带参数的构造函数

c++ - 缺少默认构造函数 - 但我没有调用它?

c# - 如何在 C# 中实现 C++ 风格的函数指针?,不使用委托(delegate)

c++ - CUDA 内核第二次运行时运行速度更快 - 为什么?

c++ - 扩展列表的大小