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

标签 c++ struct

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

比如像这样

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/

相关文章:

C++ 将 void* 转换为 int 错误

python UnicodeDecodeError : 'utf8' codec can't decode byte

c - 如何在一行中初始化一个复杂的 C 结构?

c - 通过 typedef 传递和使用结构

c++ - 如何在函数调用后初始化变量,就像 new 表达式提供的那样?

c++ - &符号 "&"在指针前面做什么?

python - 标准库中的 "common"模块是什么?

c++ - 在 C++ 中使用 #define 定义位标志

c++ - 无法确定 OpenCL 中 clEnqueueNDRangeKernel 的速度

指向结构的指针的 C typedef