这段代码报错的原因是因为类Compare中的compareArea函数访问了类CRect的成员函数display,但是CRect并没有声明为Compare的友元类,因此无法访问其私有成员函数。

解决方法是在类Compare中添加一个友元声明:

friend void CRect::display();

完整代码如下:

#include using namespace std; class CRect; class Compare { int m_length; int m_width; public: void compareArea(const Compare& r1, const Compare& r2) { double s1, s2; s1 = r1.m_length * r1.m_width; s2 = r2.m_length * r2.m_width; r1.display(); if (s1 > s2) cout << "的面积大于"; else if (s1 == s2) cout << "的面积等于"; else cout << "的面积小于"; r2.display(); } Compare(int l, int w) :m_length(l), m_width(w) {} void display()const { cout << "{" << m_length << "," << m_width << "}"; } friend void CRect::display(); }; class CRect { int m_length; int m_width; public: friend void Compare::compareArea(const Compare& r1, const Compare& r2); CRect(int l, int w) :m_length(l), m_width(w) {} void display() { cout << "{" << m_length << "," << m_width << "}"; } }; int main() { Compare r1(5, 2), r2(4, 3); r1.compareArea(r1,r2); CRect r3(6, 3), r4(4, 2); r3.compareArea(r3, r4); return 0; }

#include iostreamusing namespace std;class Compare	int m_length;	int m_width;public	void compareAreaconst Compare& r1 const Compare& r2			double s1 s2;		s1 = r1m_length r1m_width;		s2 = r2m_length r

原文地址: https://www.cveoy.top/t/topic/b1qF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录