第六周项目一(对程序进行改错)---两种方法

来源:互联网 发布:阿里云的et是什么意思 编辑:程序博客网 时间:2024/06/04 19:25
/** 程序的版权和版本声明部分* Copyright (c)2013, 烟台大学计算机学院学生* All rightsreserved.* 文件名称: object.cpp* 作者:赵晓晨* 完成日期: 2013年04月05 日* 版本号: v1.0* 输入描述:无* 问题描述:无* 程序输出:无*/# include <iostream># include <stdlib.h>using namespace std;class C{private:int x;public:C(int x){this->x=x;}int getX()const//将函数声明为const{return x;}};int main(){const C c(5);cout<<c.getX()<<endl;return 0;}


结果:

体会:

常成员函数的形式 把 const 的位置应用在函数名和括号之后

/** 程序的版权和版本声明部分* Copyright (c)2013, 烟台大学计算机学院学生* All rightsreserved.* 文件名称: object.cpp* 作者:赵晓晨* 完成日期: 2013年04月05 日* 版本号: v1.0* 输入描述:无* 问题描述:无* 程序输出:无*/# include <iostream># include <stdlib.h>using namespace std;class C{private:int x;public:C(int x){this->x=x;}int getX(){return x;}};int main(){C c(5);cout<<c.getX()<<endl;return 0;}


总结:

我更加倾向于第一种,因为直接如果将成员声明为常成员函数,则只能引用本类中的数据成员,而不能修改它们。

原创粉丝点击