2014-02-25 21 views
1

运行以下代码以使用朋友功能时出现错误。我的课XYZ1有一个朋友功能,它是ABC1类的成员函数(findMax)。我的类声明如下会员在C++中的功能为Friend功能

class XYZ1; 

class ABC1 
{ 
    int a; 
    public : 
    ABC1() 
    { 
     a =20; 
    } 
    void findMax(XYZ1 p) 
    { 
     if (p.x > a) cout<< "Max is "<<p.x; 
     else cout <<"Max is "<<a; 
    } 
}; 

class XYZ1 
{ 
    int x; 
    public : 
    XYZ1() 
    { 
     x =10; 
    } 
    friend void ABC1::findMax(XYZ1); 
}; 

main() 
{ 
    XYZ1 p; 
    ABC1 q; 
    q.findMax(p); 
} 

错误:friend3.cpp:14:7:错误: 'P' 具有不完整的类型 friend3.cpp:4:7:错误: '结构XYZ1'

的向前声明

请帮

+0

“main”的返回类型在哪里? –

回答

2

定义类XYZ1被定义后您的findMax方法。

#include <iostream> 
using namespace std; 

class XYZ1; 

class ABC1 
{ 
    int a; 
    public : 
    ABC1() 
    { 
     a =20; 
    } 
    void findMax(XYZ1 p); 
}; 

class XYZ1 
{ 
    int x; 
    public : 
    XYZ1() 
    { 
     x =10; 
    } 
    friend void ABC1::findMax(XYZ1); 
}; 

void ABC1::findMax(XYZ1 p) 
    { 
     if (p.x > a) cout<< "Max is "<<p.x; 
     else cout <<"Max is "<<a; 
    } 

int main() 
{ 
    XYZ1 p; 
    ABC1 q; 
    q.findMax(p); 
    return 0; 
} 
0

你必须有class XYZ1一个完整的声明,以便编译器能够编译使用它的代码。

所以移动的void findMax(XYZ1 p)实施class XYZ1声明如下:

class ABC1 
{ 
    ... 
    void findMax(XYZ1 p); 
}; 

class XYZ1 
{ 
    ... 
    friend void ABC1::findMax(XYZ1 p); 
}; 

void ABC1::findMax(XYZ1 p) 
{ 
    ... 
} 
+0

非常感谢...它运作良好 – user3284709

+0

不客气:)您可以通过点击旁边的V来接受答案... –