使用类函数中的类数据成员作为默认值 c++
Using a class data-member in a class function as default value, c++
在 c++ 中,我试图将类数据设置为类中函数的默认值,但它在构建它时抛出了一个错误。代码如下所示:
class tree{
public:
node *root;
bool push(node what, node* current = root, int actualheight = 1){
编译器引发错误
从函数位置无效使用非静态数据成员"tree::root"
如果我删除"当前"的默认值,它可以正常工作。可能是什么问题?我该如何解决它?
函数参数列表中没有this
指针,因此不能在默认参数中引用类成员。
解决方案是重载函数:
bool push(node what, node* current, int actualheight = 1){...}
bool push(node what){ return push(what, root); }
现在,当您使用一个参数调用push
时,它会转发到另一个重载,提供root
作为第二个参数,这完全符合您想要实现的目标。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 具有默认值的引用获取函数
- 当给定默认值时,为什么此模板参数推导失败
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 格式化浮点值:返回默认值
- 如何将数组部分初始化为某个默认值?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 创建一个包含 c++ 默认值的环境文件
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- Makefile g++ 使用命令行中的 -D 变量进行编译,默认值
- Switch 语句(字符串)一直选择默认值,除非其为零
- 如何使用默认值将枚举声明为 extern
- 如何在提升程序选项中设置矢量<矢量>的默认值<string>
- 如何使用默认值为构造函数中的枚举赋值?
- 变量始终在函数中重置为默认值
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 函数不返回默认值
- 具有公共范围与专用范围的默认值的C++的不同行为
- 在 c++ 中,如果我创建一个接受一个具有默认值的参数的构造函数 - 它会用作默认(空)构造函数吗?
- 实例化时结构字段中的默认值