开发者

Can two classes access each other?

If I have two classes called A and B,

Note: The following doesn't compile.

class A
{
public:
   static void funcA() {}
   void call_funcB() { B::funcB(); } // call class B's function
};

class B
{
public:
   static void funcB() {}
   void call_funcA() { A::funcA(); } // call class A's function
};

Errors:

error C2653: 'B' : is not a class or namespace name
error开发者_Go百科 C3861: 'funcB': identifier not found

Can you call the static functions of each class?


You have to do this:

class A
{
public:
   static void funcA() {}
   void call_funcB() ;
};

class B
{
public:
   static void funcB() {}
   void call_funcA() { A::funcA(); } // call class A's function
};

   void A::call_funcB() { B::funcB(); } // call class B's function

This allows A::call_funcB() to see the B declaration.


You need to give the compiler a tip that the other class with be defined because it's a circular dependency.

class B;

class A { ... };

class A; // assuming separate file

class B { ... };


You could make funcA and funcB Friend methods.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜