gpt4 book ai didi

c++ - struct c++ 中的默认参数

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:17 25 4
gpt4 key购买 nike

我想使用变量作为结构中函数的默认参数

比如像这样

struct A {   
int b;
A () {
b = 0;
}
int func(int t = b) {
...
}
}

对不起,我第一次发问题,编码不好

但我不断收到错误,我也尝试使用 static int,但出现运行时错误。

有什么方法可以使用 b 作为默认参数吗?!

当对 b 使用 static int 时,我得到:(mx 是 b,wavelet_tree 是 A)

/tmp/cc3OBfq8.o: In function `main':
a.cpp:(.text+0x2dc): undefined reference to `wavelet_tree::mx'
/tmp/cc3OBfq8.o: In function `wavelet_tree::wavelet_tree()':
a.cpp:(.text._ZN12wavelet_treeC2Ev[_ZN12wavelet_treeC5Ev]+0x42): undefined reference to `wavelet_tree::mx'
/tmp/cc3OBfq8.o: In function `wavelet_tree::build(int*, int, int)':
a.cpp:(.text._ZN12wavelet_tree5buildEPiii[_ZN12wavelet_tree5buildEPiii]+0x66): undefined reference to `wavelet_tree::mx'
a.cpp:(.text._ZN12wavelet_tree5buildEPiii[_ZN12wavelet_tree5buildEPiii]+0x73): undefined reference to `wavelet_tree::mx'
a.cpp:(.text._ZN12wavelet_tree5buildEPiii[_ZN12wavelet_tree5buildEPiii]+0x7f): undefined reference to `wavelet_tree::mx'
collect2: error: ld returned 1 exit status

最佳答案

简单地重载函数

struct A
{
int b;
A () : b(0) {};

int func(int t) { return whatever();};
int func() {return func(b);};
};

这样,b 可以是 A 的任何成员(无论 static 与否),或者任何可访问的变量,其中 func()定义等

关于c++ - struct c++ 中的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59488414/

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