C++ 类之间友元函数和函数声明的错误解决方法
#include
class Compare;
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(); };
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 << "}"; } };
void CRect::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; }
在类 CRect 中,需要添加一个函数声明 void display(),以便在类 Compare 中使用。同时,在类 CRect 中,需要添加一个友元函数声明 friend void Compare::compareArea(const Compare& r1, const Compare& r2);,以便在类 Compare 中使用。修改后的代码如下:
#include <iostream>
using namespace std;
class Compare;
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();
};
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 << "}";
}
};
void CRect::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;
}
原文地址: https://www.cveoy.top/t/topic/nl3c 著作权归作者所有。请勿转载和采集!