结构 c++ 中的默认参数

Default argument in struct c++

本文关键字:默认 参数 c++ 结构      更新时间:2023-10-16

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

比如这样

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

抱歉编码不好,这是我第一次发布问题

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

有没有办法使用 b 作为默认参数?!

当对 b 使用静态 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()的任何变量,等等。