不带参数的函数

function without a parameter c++

本文关键字:函数 参数      更新时间:2023-10-16

我想了解如何编写没有参数的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(){}

由于getHeightNode的成员,因此它可以访问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;}

你也可以通过不同的命名方法和数据。

这就是为什么getHeightsetHeight经常被使用。有些人更喜欢成员访问方法为height的约定,因此将成员数据重命名为int height_或诸如此类的。

我认为你在概念上误解了一些东西。

从面向对象的角度来看,"什么"是你想要得到的高度?

对于你的第一个函数"Node *N"参数是对象。

现在,当您想从函数调用和声明中取出参数时,它必须与您给出的完全任意的"高度"一起工作,或者您需要将getheight()作为Node类的成员,以便返回Node的高度