前向声明类,拆分变量和函数

时间:2017-04-03 13:50:08

标签: c++ class dependencies declaration forward

假设我在C ++中有两个A和B类。这两个类都有一些私有变量,都是朋友。这两个类都有一些简单的公共函数(在这些函数中没有函数调用),它们使用A和B中的变量。

我给你一个代码示例:

    class A;
    class B;

    //Here I declare the variables

    class A{
        friend class B;
        private:
        double a=2.;
        };

    class B{
        friend class A;
        private:
        double b=2.;
        };

    //Now I try to declare the functions
    //I know, I do a redefinition now, but actually I just 
    //like to define the functions after the variables, such
    //that the compiler knows the variables my functions 
    //like to use.

   class A{
        public:
        double fun(B Btest){return Btest.b+2*a;}    
        };

    class B{
        public:
        double fun(A Atest){return Atest.a+b;}  
        };


    int main(){

        A Atest;
        B Btest;

        double s=Btest.fun(Atest);
        return 0;
        }

如果我是编译器,我也不会接受该代码,因为可能存在丑陋的循环依赖,但在我的情况下,我确信,没有圆圈。有没有一种很好的方法告诉我的编译器做这样的事情?

这是解决方案,我并没有真正理解声明和定义的概念:

What is the difference between a definition and a declaration?

    class A;
    class B;

    class A{
        friend class B;
        public:
        double fun(B);
        private:
        double a=2.;
        };

  class B{
       friend class A;
       public:
       double fun(A);   
       private:
       double b=2.;
    };

    double A::fun(B Btest){return Btest.b+a;} 
    double B::fun(A Atest){return Atest.a+b;}   

    int main(){

        A Atest;
        B Btest;

        double s=Btest.fun(Atest);
        return 0;
        }

0 个答案:

没有答案