【题目】下面的程序存在编译错误。有两种方法可以修改,请给出这两种修改方案,在报告中说明你倾向于用哪一种?为什么?处理此类问题的原则是什么?
- class C
- {private:
- int x;
- public:
- C(int x){this->x= x;}
- int getX(){return x;}
- };
- void main()
- {
- const C c(5);
- cout<<c.getX();
- system("pause");
- }
- 方案一:
-
- class C
- {private:
- int x;
- public:
- C(int x){this->x= x;}
- int getX(){return x;}
- };
- void main()
- {
- C c(5); //去掉const
- cout<<c.getX();
- system("pause");
- }
-
- class C
- {private:
- int x;
- public:
- C(int x){this->x= x;}
- int getX() const {return x;} //加上const,成为常成员函数
- };
- void main()
- {
- const C c(5);
- cout<<c.getX();
- system("pause");
- }