C++类定义与使用的基本语法
1、类的声明和函数的声明很像,都可以写在主函数的前面:
class Intcell
{
public:
Intcell( )
{ storedvalue = 0; }
Intcell(int init){storedvalue=init;}
void write(int x){storedvalue=x;}
int read(){return storedvalue;}
private:
int storedvalue;
};
这里,我们声明了一个叫Intcell的类。
2、这一个类包括两个标签:Public和Private。
Public中的成员是外部可以通过类的对象进行访问的,就如他的名字公开的。
Private内的数据是不可再外部直接访问的。
3、类主要包括两类成员,数据和成员函数。
成员函数一般叫做方法
4、构造函数一般用于初始化对象。
Intcell( )
{ storedvalue = 0; }
Intcell(int init){storedvalue=init;}
5、主程序建立一个对象并初始化:
Intcell m(6);
6、成员方法的使用:
m.read():读取存储的数据
m.write(6):写入存储的数据
7、结果:
6
7符合条件。
8、全部代码如下:
#include <iostream>
using namespace std;
class Intcell
{
public:
Intcell( )
{ storedvalue = 0; }
Intcell(int init){storedvalue=init;}
void write(int x){storedvalue=x;}
int read(){return storedvalue;}
private:
int storedvalue;
};
int main()
{
Intcell m(6);
cout<<m.read()<<endl;
m.write(7);
cout<<m.read()<<endl;
return 0;
}