1.类的接口
注意:
①默认参数在接口中被定义,在实现中被忽略。
②使用explicit意味着单参数构造函数不能用来创建隐式临时对象,这样在定义类的对象或赋值时,编译器能正确分析出类型不匹配的问题。
#ifndef IntCell_H
#define IntCell_H
/*
仿真int型存储单元的类
*/
class IntCell
{
public:
explicit IntCell(int initialValue = 0);
int read() const;
void write(int x);
private:
int storeValue;
};
#endif
2.类的定义
注意:
①成员函数需声明为类的一部分,否则将被认为是全局的。
#include"IntCell.h"//在当前目录搜索,再去默认搜索目录搜索
IntCell::IntCell(int initialValue):storeValue(initialValue){}
//默认的初始值在接口.h中定义,在实现时被忽略
int IntCell::read() const
{
return storeValue;
}
void IntCell::write(int x)
{
storeValue = x;
}
3.使用定义的类
#include<iostream>
#include"IntCell.h"
using namespace std;
void main()
{
IntCell a;
IntCell b(2);
cout << "a=" << a.read() << endl;//输出字符串用双引号
cout << "b=" << b.read() << endl;
a.write(3);
cout << "after input 3, a = " << a.read() << endl;
}