#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 << '}'; } };

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 r(1, 1); compareArea(r1, r2); return 0; }

为什么compareArea用不了内容:在main函数中调用compareArea时,需要传入两个Compare类的对象作为参数,但是compareArea函数并不是一个全局函数,它是Compare类中的成员函数,只能通过Compare类的对象来调用。因此,直接调用compareArea是无法通过编译的。需要先创建一个Compare类的对象,然后通过该对象来调用compareArea函数。


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

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