开发者

Class declaration without static

开发者 https://www.devze.com 2023-02-18 19:41 出处:网络
I have a class Queue; I have these v开发者_Go百科ariables defined in that class... int head, tail;

I have a class Queue; I have these v开发者_Go百科ariables defined in that class... int head, tail;

One of the functions check if (head==tail), however I cannot declare head and tail to be equal to 0 in that function or else every time i call that function it will reset itself...

How can i declare head and tail to be equal to 0 without static variables...do i need to make a default constructor?


You can do that in the constructor; more specifically in the initialization-list of the constructor!

class Queue
{
  int head, tail;
  public:
    Queue() : head(0), tail(0) {}
          // ^^^^^^^^^^^^^^^^ this is called initialization-list!
};

In the initializatin-list you can initialize all your variables!

If that looks scary, you can also do this:

class Queue
{
  int head, tail;
  public:
    Queue() 
    {
        head = 0;
        tail = 0;
    }
};

But first approach is preferred, as that is initialization, and the second one is assignment!

Read this FAQ : Should my constructors use "initialization lists" or "assignment"?


Yes, in C++ any non-static variables have to be initialized in a method, and a good choice is the constructor (or perhaps an init() method, depending on what you're doing)

0

精彩评论

暂无评论...
验证码 换一张
取 消