开发者

Access to derived class variable in C++?

I am trying to access a variable inside derived class.

     printf("%c", God.m_Please.me);

Inside God class declaration I have declared m_Please as

     private:
     Please *m_Please

and helpme is a variable declared in a class derived from Please

    class Help : public Please

and me is defined as

    unsigned char me[1000];

when I try to compile this I get error

error C2228: left of '.me' must have class/struct/union type

I am Using Visual Studio 6.0

Please reply back....

orward declare "class Please;" before God – wqking That开发者_开发知识库 helped to remove the first error :) but I still get 2 other errors

Thanks,


Please* Please is private. You cannot access a private member from a derived class. It must be protected.

class Please{
  protected:
  Please* m_Please;
  int pplHelped;
};

class Help : public Please {

  void whatever(){
      //assume m_Please was initialized elsewhere
      Please::m_Please->pplHelped; //do something with pplHelped
  }
};

If you are trying to access the base member variable through an instance of the derived class, it should be declared public in the base class.

class Please{
  public:
  Please* m_Please; //init this somewhere
  int pplHelped;
};

class Help : public Please{
};

void somefunc(){
  Help God;
  //assume m_Please was initialized in Constructor
  printf("%d\n", God.m_Please->pplHelped;
}


m_Please is a pointer (Please*). You cannot use operator . on pointers.

The correct way to do it would be

printf("%c",God.m_Please->me);


God.m_Please->me
-> instead .
m_Please is a pointer


God.m_Please.me is inreconcilable with PLease *m_Please. As m_Please is a pointer, use God.m_Please->me. Still, that provides access to the character array, so you either need to specify which character in the array printf() should display (e.g. me[0]), or use the printf format "%s" which can display ASCIIZ strings.


You're syntax is confusing. A complete sample code would be appreciated.

If I understand you correctly, you are trying to access a private class member from a derived class. That won't work unless the derived class is declared as a friend to the base class. The proper way would be to use protected instead of private.

Oh, and as others suggested, use -> instead of . for accessing members of a pointer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜