gpt4 book ai didi

c++ - 隐式转换的多参数

转载 作者:行者123 更新时间:2023-11-30 02:07:56 24 4
gpt4 key购买 nike

对于具有多个参数的构造函数...

例如:

class C {
public:
C(int a=1, int b=2){ cout << a << ", " << b << "\n"; }
}

int main(){
C a(10), b = 20;
}

output:
10, 2
20, 2

如何为第二个参数赋值?这样我就可以在不知道默认值的情况下得到“1、20”?还是我必须始终为前面的参数赋值,然后才能使用后面的参数?

我如何隐式分配所有参数?如果我不能那样做,为什么?对于上面的示例(因为我是 C++ 的新手),我曾经以为我会得到“10, 20”作为输出。

最佳答案

Or is that that I must always assign value to the argument that precedes before I can use the arguments behind?

是的。否则,编译器应该如何知道哪个参数应该用于哪个参数?

但是,有一些方法可以做到这一点。例如,

struct C {
enum { DefaultA = 1, DefaultB = 2 };
C(int a = DefaultA, int b = DefaultB) { /* ... */ }
};

C object(C::DefaultA, 20);

或者,如果您有很多具有不同“默认值”的参数:

struct CParams {
int a, b;
CParams() : a(1), b(2) { }
};

struct C {
C(CParams x) { /* ... */ }
};

CParams params;
params.b = 20;
C object(params);

关于c++ - 隐式转换的多参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7342802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com