不带参数的函数
function without a parameter c++
我想了解如何编写没有参数的getheight
函数,它仍然可以工作。
my node.h file
Node();
~Node();
int getHeight(Node* node);
//int getHeight(); without a parameter but those two can perform the same work
int data;
int height;
Node* left;
Node* right;
node.cpp:
int node::height(Node *N){
if (N == NULL)
return 0;
return N->height;
}
//if I do not put the Node pointer into this function as a parameter, how should I write this function?
int node::height(){}
由于getHeight
是Node
的成员,因此它可以访问Node
对象的成员。你可以点击return height;
。这与return this->height;
相同。
当然,他们不做"相同的工作"。一个返回作为参数的指针传递的Node
的高度,而另一个返回this
的高度。实际上,您似乎根本没有一个很好的理由使用接受指针的版本。它尤其不应该是成员函数,因为它不依赖于this
的状态。如果您真的想要一个具有这种签名的函数,我建议将其设置为使用成员getHeight
:
int getHeight(Node *N) {
if (N == NULL)
return 0;
return N->getHeight();
}
如果你在接收空指针时返回0的唯一原因是为了避免运行时错误,我建议让函数接受引用:
int getHeight(Node& N) {
return N.getHeight();
}
[这可能不是你的问题,但是评论太长了。]
当试图写入:
int node::height(){}
你可能已经试过了:
int node::height(){ return height;}
这当然会导致编译错误。一种方法是返回height
成员的值,但实际上返回指向成员函数本身的指针。
你可以写:
int node::height(){ return this->height;}
你也可以通过不同的命名方法和数据。
这就是为什么getHeight
和setHeight
经常被使用。有些人更喜欢成员访问方法为height
的约定,因此将成员数据重命名为int height_
或诸如此类的。
我认为你在概念上误解了一些东西。
从面向对象的角度来看,"什么"是你想要得到的高度?
对于你的第一个函数"Node *N"参数是对象。
现在,当您想从函数调用和声明中取出参数时,它必须与您给出的完全任意的"高度"一起工作,或者您需要将getheight()作为Node类的成员,以便返回Node的高度
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数