c++学习2011-02-27

    技术2022-05-20  41

    背景:友元 前向声明

     

    源代码:#include <iostream>using namespace std;

    //class Car;

    class Boat{private: float Weight; public: Boat(float weight = 0) {  Weight = weight; } friend float totalWeight(Boat &a,Car &b);};

    class Car{private: float Weight;public: Car(float weight = 0) {  Weight = weight; } friend float totalWeight(Boat &a,Car &b); };

     

     

    float totalWeight(Boat &a,Car &b){ float c; c = a.Weight + b.Weight; return c; }

     

    int main(){ Boat aa(100.1); Car bb(200.2);  cout << totalWeight(aa,bb) << endl; return 0;}

     

    错误提示:syntax error : identifier 'Car' //语法错误:标识符Car'Weight' : cannot access private member declared in class 'Boat' //不能在类Boat中公然的访问私有成员

    错误分析:Boat类和Cat类互相引用

    研究结果(知识扩展):我在开始时没有加上前向声明class Car,所以导致错误。这个错误能在编译阶段查出来,是静态错误,语法错误。


    最新回复(0)