friend class doesn't do well with me?

71 views Asked by At

I am trying to deal with friend class for the first time. I wrote the code below:

class Kind{

private:
    friend class Type;
    int x;

public:
    Kind(){ x=0; }
    void setX(int X) { x =X; }
    int getX() { return x; }

    };

class  Type: public Kind {
    public:
    friend class Kind;
    Type(){ }
    Kind root;
    root.x=3;

};

The compiler tells me that I can not do root.x=3;, What is the problem??

2

There are 2 answers

0
JaredPar On BEST ANSWER

The problem is your trying to execute a statement in a place where the compiler is expecting member declarations. Try putting it into a method

class Type : public Kind {
  ...
  void Example() {
    Kind root;
    root.x = 3;
  }
};
0
Mahesh On

You cannot do the assignment as part of the class declaration. Do it in a member function instead.