1 下面类定义中有六处语法错误请指出并改正:class A private static int cnt; int x;public Aint _xcnt0 x = _x; cnt++; Aconst A& a xax cnt++; ~A cnt--; int get const return x; void setint _x x =
- A类构造函数中的cnt++应该放在语句块中,不能在初始化列表中使用。
- A类count函数声明中的const应该放在函数定义中。
- B类构造函数中应该使用初始化列表来初始化a,而不是在构造函数体中重新创建一个A对象并赋值给a。
- B类中setX函数应该去掉const修饰符。
- B类中setV函数应该保留const修饰符,因为该函数不会修改成员变量a的值。
- A类中的cnt应该在类外进行定义和初始化。
改正后的代码如下:
class A { private: static int cnt; int x; public: A(int _x) { x = _x; cnt++; } A(const A& a) :x(a.x) { cnt++; } ~A() { cnt--; } int get() const{ return x; } void set(int _x) { x = _x; } static int count() { return cnt; } };
int A::cnt = 0;
class B { private: A a; int v; public: B(int _x, int _v) : a(_x), v(_v) {} int getX() const { return a.get(); } int getV() const { return v; } void setX(int _x) { a.set(_x); } void setV(int _v) const { v = _v; } }
原文地址: https://www.cveoy.top/t/topic/fD71 著作权归作者所有。请勿转载和采集!