将参数初始化为构造函数,而不是第一个

Initialize parameter into constructor, other than the first one

本文关键字:第一个 构造函数 参数 初始化      更新时间:2023-10-16

我想在以下情况下明确更改structor中的第二个参数。有可能,如果是的话,如何?

struct foo{
    int x;
    int y;
    foo(int a=4, int b=6){
        x=a;
        y=b;
    }
};
int main(){
    foo *f = new foo();
    cout<<f->x<<" "<<f->y<<endl;
   //4 6 
    foo *g = new foo(3,4);
    cout<<g->x<<" "<<g->y<<endl;
    //3 4
    foo *h = new foo(3);
    cout<<h->x<<" "<<h->y<<endl;
   //3 6
   //Can something like this be 
   //done in C++, if I want
   //to change the value of the 
   //second variable only
    foo *k = new foo(b = 13);
return 0;
}

有可能,如果是,如何?

构造函数不可能。通常,C 不支持命名的关键字参数对函数,即使您有默认值,也无法跳过参数,如果您想在其之后通过非默认值。

,如果使用默认成员启动器:

struct foo{
    int x = 4;
    int y = 6;
};
int main(){
    foo f {.y = 4};
}

您可以通过TAG派遣来实现类似的目标;无需将来的标准:

struct foo{
    int x = 4;
    int y = 6;
    enum Xtag { Xinit };
    enum Ytag { Yinit };
    foo(int a, int b) : x(a), y(b) {}
    foo(Xtag, int a)  : x(a) {}
    foo(Ytag, int b)  : y(b) {}
};
int main(){
    foo f(foo::Yinit, 4);
}

使用lambda的解决方案,可以在不修改现有类的情况下使用。以下处理您对foo的定义:

auto make_foo_x4 = [](int b) {
    return foo(4, b);
};
foo f = make_foo_y(4);

不利的一面是我们必须明确重复x的默认值,因此,如果在类别中更改默认值,这可能会破坏假设。