开发者

Can member function arguments be of the same class type?

//node.h 
class node 
{
      public:
            void sort(node n);

};

I didn't try the code yet . But It's interesting to know if is this a valid case and Why ?

Edit :

This leads me to another question : Can I declare FOO inside a member function like this ?

//FOO.h
Class FOO
{
   public:
   void sort(int n) ;
   void swap(int x , int y ); 
}

//FOO.cpp

void FOO::sort (int n)
{
   开发者_如何学Python  FOO obj;
     obj.swap(3 , 5) ;
}


Yes, that's perfectly valid. If you couldn't do that, how could you write copy constructors?

A similar, but not valid case, is including the same type as a member of your class/struct.

struct Foo
{
  Foo m_foo;
};

You can't do that, because it's essentially a circular definition, and if you had:

struct Foo
{
  Foo m_foo;
  Foo m_bar;
};

Then a Foo would be 2 Foos, which would be 4 Foos, which would be 8 Foos etc. which makes no sense.

You can, on the other hand, have pointers to the same type:

struct Foo
{
  Foo* m_foo;
};

Because a pointer to Foo isn't the same as Foo. A pointer is a pointer, no matter what it points to, so there is no circular definition or dependencies.


Having now established that your question is solely related to passing node by value in a member (rather than passing node* or node&) the answer is still yes. You can even define the body of the member within the class is you so wish.

As to why, think of things from the compiler's point of view. As it parses the class all it really needs to know are what data members there are within it and what the function member signatures are. None of the function member definitions need to be parsed at this point so the compiler would not be alarmed at the prospect of seeing an actual node as an argument. Only when it's finished parsing the data and signatures would it go back and actually deal with the function member definitions and at that point it knows precisely what a node is.

In answer to your second question you can define instances of your class within the member (for the same reason).


yes, you can. its a valid case.

you can find some sample in c++ standard libs :

string& append( const string& str );


This is done quite often. A copy constructor is a a good example:

class Apple {  
public:  
    Apple();  
    Apple(const Apple&);  
};  


The short answer is Yes:

The long answer is:

$9.2/2- "A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments and constructor ctor-initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification."

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜