/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:this指针
* 作 者: 张培培
* 完成日期: 2011年 03月 26日
* 版 本 号:
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
* 程序头部的注释结束*/
方法一:
#include <iostream>
using namespace std;
class C
{
private:
int x;
public:
C(int x){this->x = x;}
int getX(){return x;}
};
void main()
{
C c(5);
cout<<c.getX()<<endl;
system("pause");
}
方法二:
#include <iostream>
using namespace std;
class C
{
private:
int x;
public:
C(int x){this->x = x;}
int getX() const {return x;}
};
void main()
{
const C c(5);
cout<<c.getX()<<endl;
system("pause");
}
方法一:在main函数中定义对象时,把const去掉;
方法二:在public函数中,声明定义getX()时在后面加上const;
我更倾向于第二种修改方案。
本文通过两个示例介绍了C++中this指针的基本使用方法。演示了如何通过this指针访问类成员变量,并对比了常量成员函数中this指针作为常量的特点。
416

被折叠的 条评论
为什么被折叠?



