C++ 代码分析:类之间关系与函数调用错误
#include
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: 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); r1.compareArea(r1, Compare(1, 1)); return 0; }
这段代码有几个问题:
-
在类Compare中的compareArea函数中,使用了类CRect中的成员变量m_length和m_width,但是CRect类并没有在Compare类中声明或定义,需要添加一个类的声明或定义。
-
在CRect类中,friend声明了Compare类中的compareArea函数,但是该函数中并没有使用CRect类的成员变量或函数,因此这个friend声明是多余的。
-
在main函数中,使用了未定义的函数compareArea,应该改为调用Compare类中的compareArea函数。
下面是修改后的代码:
#include
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: 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); r1.compareArea(r1, Compare(1, 1)); return 0;
原文地址: https://www.cveoy.top/t/topic/nl57 著作权归作者所有。请勿转载和采集!