C++ 默认参数类成员
c++ default parameters class members
class bst
{
private:
typedef struct nod
{
int data;
nod* left;
nod* right;
nod(int key):data(key),left(NULL),right(NULL){}
}node;
node* root;
public:
void create();
void add(int key,node*curr=root);
void c2ll();
void print(){}
代码无法编译...我收到以下错误。
ain.cpp: In function ‘int main()’:
main.cpp:7:12: error: call to ‘void bst::add(int, bst::node*)’ uses the default argument for parameter 2, which is not yet defined
bt.add(50);
^
In file included from bst.cpp:1:0:
bst.h:14:8: error: invalid use of non-static data member ‘bst::root’
node* root;
^
bst.h:19:28: error: from this location
void add(int key,node*curr=root);
^
bst.h:14:8: error: invalid use of non-static data member ‘bst::root’
node* root;
^
bst.cpp:10:34: error: from this location
void bst::add(int key,node* curr=root)
欢迎任何建议...我试图避免编写包装器方法,而是使用 c++ 提供的默认功能
根据
C++标准(8.3.6 默认参数)
- 。同样,非静态成员不得在默认参数中使用,即使它未被计算,除非它显示为 类成员访问表达式 (5.2.5) 的 ID 表达式,除非它 用于形成指向成员 (5.3.1) 的指针。[ 示例:该 以下示例中 X::mem1() 的声明格式不正确 因为没有为用作的非静态成员 X::a 提供对象 初始值设定项。
int b;
class X {
int a;
int mem1(int i = a); // error: non-static member a
// used as default argument
int mem2(int i = b); // OK; use X::b
static int b;
};
您可以重载函数add
。例如
void add( int key );
void add( int key, node *curr );
默认情况下,第一个函数将使用root
。它可以简单地调用第二个函数,作为第二个参数传递节点根。
问题出在方法的定义中:
void add(int key,node*curr=root);
root
不是在你使用它的上下文中定义的。如果你的意思是成员变量node* root
,则无法在成员函数中默认为成员变量,但您可以将 NULL(0) 设置为默认值并在定义中检查它。
void bst::add ( int key,node*curr=NULL)
{
if(curr==NULL) {
curr= this->root;
}
}
有两种方法。
要么使用"魔术"默认值:
void add(int key, node* curr = NULL)
{
if (curr == NULL)
curr = root;
// ...
}
或者完全放弃默认值并使用重载:
void add(int key, node* curr)
{
// ...
}
void add(int key)
{
add(key, root);
}
我个人更喜欢后者,但你根本不应该在树的界面中公开节点类型,因为这会让树的用户破坏它的平衡。
像这样使用:
const node* root = NULL;
void add(int key,node*curr=root);
您可以在此处查看实际运行示例:http://ideone.com/tJ1r29
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 如何将lambda作为模板类的成员函数参数
- 将成员函数指针作为参数传递给模板方法
- c++构造函数成员初始化:传递参数
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 模板化检查是否存在带有参数列表的类成员函数?
- 如何将类成员方法的参数列表自动填充写入可变参数?
- 为什么我需要在成员发起器列表中重复基类的模板参数?
- C++向量默认为成员参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 当类成员参数具有相同的名称时,如何定义构造函数?
- 类成员参数中的Constexpr
- 允许通过指向方法的成员参数的指针来推断模板参数所指向的成员类型
- 为什么未调用的模板类成员 *参数* 被实例化
- 如何访问指向C++类模板中成员参数的指针
- 我们是否需要在嵌套类型的成员参数前面加上"::"?
- 设计模式- c++运行时成员参数的实例化