//--《C++捷径教程》读书笔记--Chapter 11--类(第二部分)
//--Chapter 11--类
//--03/12/2006 Sun.
//--Computer Lab
//--Liwei
//--程序#2 对类成员得访问
#include <iostream>
using namespace std;
class myclass{
int a;
public:
int b;
void setab(int i);
int geta();
void reset();
};
void myclass::setab(int i)
{
a=i; b=i*i;
}
int myclass::geta()
{ return a; }
void myclass::reset()
{
setab(0);
}
//=======================
int main()
{
myclass ob;
ob.setab(5);
cout<<"ob after setab(5): ";
cout<<ob.geta()<<' '<<ob.b<<'/n';
ob.b=20;
cout<<"ob after ob.b=20: ";
cout<<ob.geta()<<' '<<ob.b<<'/n';
ob.reset();
cout<<"ob after ob.reset(); ";
cout<<ob.geta()<<' '<<ob.b<<'/n';
return 0;
}
本文通过一个具体的C++程序实例,展示了如何定义类及其成员,并演示了如何使用公有成员函数来设置和获取私有成员变量的值,同时讨论了直接访问公有成员的情况。

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



