C++|接口定义(声明)、实现、使用的分离来实现编程模块化

模块化(modularity)能够实现接口(interface)定义(definition,或声明,declaration)、实现(implementaion)、使用(或调用,calling)的分离,并且能够分散到同一项目的不同文件中,通过预处理指令include建立联系,且最后能通过链接器实现链接。同时,使函数库或类库能得以实现。

1 接口放到头文件(或放到单文件的前面)

Typically, we place the declarations that specify the interface to a module in a file with a name indicating its intended use.

//vector.h
class Vector {
public:
Vector(int s);
int size();
double& operator[](int i);
~Vector() { delete[] elem; } // destructor: release resources, inline
private:
double* elem; // pointer to the elements
int sz; // the number of elements
};
double read_and_sum(int s);

2 接口实现

To help the compiler ensure consistency, the .cpp file providing the implementation of Vector will also include the .h file providing its interface:

//vector.cpp
#include <iostream>
#include "vector.h"
using namespace std;
Vector::Vector(int s) // constr uct a Vector
{
sz = s;
elem = new double[s];
for (int i=0; i!=s; ++i)
elem[i]=i; // initialize elements
}

double& Vector::operator[](int i) // element access: subscripting
{
return elem[i];
}
int Vector::size()
{
return sz;
}
double read_and_sum(int s)
{
Vector v(s); // make a vector of s elements
//for (int i=0; i!=v.size(); ++i)
//cin>>v[i]; //read into elements
double sum = 0;
for (int i=0; i!=v.size(); ++i)
sum+=v[i]; //take the sum of the elements
return sum;
}

3 接口使用(访问或调用)

This declaration would be placed in a file Vector.h, and users will include that file, called a header file, to access that interface.

//user.cpp
#include <iostream>
#include "vector.h"
using namespace std;
void main()
{
cout<< read_and_sum(100)<<endl; //4950
system("pause");
}

-End-

发表评论
留言与评论(共有 0 条评论)
   
验证码:

相关文章

推荐文章

'); })();