类的声明
C++类由成员构成,成员既可以是变量也可以是函数
构建一个IntCell类举例
class IntCell{
public:
IntCell()
{
storedValue=0;
}
IntCell(int initialValue)
{
storedValue = initialValue;
}
int read()
{
return storedValue;
}
void write(int x)
{
storedValue=x;
}
private:
int storedValue;
};
其中private表明storedValue是私有变量,对外不可见(透明)
一种更简洁的方式
class IntCell
{
public:
explicit IntCell(int initialValue=0)
:storedValue(initialValue){}
int read() const
{
return storedValue;
}
void write(int x)
{
storedValue = x;
}
private:
int storedValue;
};
IntCell中的构成函数中使用了默认值,如果构建IntCell类对象时没有传入参数storedValue会默认为0
第五行为初始化列表,可以直接初始化数据成员, 当数据成员具有复杂初始化过程的类类型时可以节省很多时间;在数据成员为const情况下意味着对象在构建之后就不能够被修改,那么数据成员的值只能在初始化列表中进行初始化
IntCell的构造函数是explicit,所有的单参数构造函数都必须是explicit以避免后台的类型转换
只检测但是不改变对象状态的成员函数为访问函数,如IntCell中的read函数;改变状态的是修改函数,如IntCell中的write函数
类函数调用示例
#include<iostream>
using namespace std;
/*class IntCell{
public:
IntCell()
{
storedValue=0;
}
IntCell(int initialValue)
{
storedValue = initialValue;
}
int read()
{
return storedValue;
}
void write(int x)
{
storedValue=x;
}
private:
int storedValue;
};
*/
class IntCell
{
public:
explicit IntCell(int initialValue=0)
:storedValue(initialValue){}
int read() const
{
return storedValue;
}
void write(int x)
{
storedValue = x;
}
private:
int storedValue;
};
int main(){
IntCell m, n(6);
cout<<m.read()<<endl;
cout<<n.read()<<endl;
m.write(5);
n.write(7);
cout<<m.read()<<endl;
cout<<n.read()<<endl;
return 0;
}
接口与实现分离
假设我们在IntCell.h中提供接口,在IntCell.cpp进行实现,在main.cpp使用
IntCell.h代码
#ifndef IntCell_H
#define IntCell_H
class IntCell
{
public:
explicit IntCell(int initialValue = 0);
int read() const;
void write(int x);
private:
int storedValue;
};
#endif
在文件开始时先要确认符号IntCell_H没有被定义(#ifndef),如果以及被定义则什么都不做,如果没有被定义则进行定义
IntCell.cpp代码
#include"IntCell.h"
IntCell::IntCell(int initialValue):storedValue(initialValue)
{
}
int IntCell::read() const
{
return storedValue;
}
void IntCell::write(int x)
{
storedValue = x;
}
main.cpp代码
#include<iostream>
#include"IntCell.h"
using namespace std;
int main(){
IntCell m, n(6);
cout<<m.read()<<endl;
cout<<n.read()<<endl;
m.write(5);
n.write(7);
cout<<m.read()<<endl;
cout<<n.read()<<endl;
return 0;
}
本文通过IntCell类的声明和实现,展示了C++中的类构造、成员函数、封装以及初始化列表的使用。类提供了read和write函数来访问和修改私有变量storedValue,同时强调了explicit关键字防止隐式类型转换。此外,还介绍了接口与实现分离的原则,分别在IntCell.h和IntCell.cpp中定义和实现类的功能。在main.cpp中,演示了如何创建并操作IntCell对象。
1万+

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



