[英]How can I use my own made Array header file in my main program c++?
I have created my own header file, this is how we were asked to do it, but what arguments should I use in my main program to call this header file and create an Array. 我已经创建了自己的头文件,这就是我们被要求这样做的方法,但是我应该在主程序中使用哪些参数来调用这个头文件并创建一个数组。
My header file looks like this: 我的头文件如下所示:
#ifndef ARRAY_H
#define ARRAY_H
class Array {
public:
Array(int size) : _size(0), _arr(0) {
// Call resize to initialize oneself
resize(size) ;
}
Array(const Array& other) : _size(other._size) {
_arr = new double[other._size] ;
// Copy elements
for (int i=0 ; i<_size ; i++) {
_arr[i] = other._arr[i] ;
}
}
~Array() {
delete[] _arr ;
}
Array& operator=(const Array& other)
{
if (&other==this) return *this ;
if (_size != other._size) {
resize(other._size) ;
}
for (int i=0 ; i<_size ; i++) {
_arr[i] = other._arr[i] ;
}
}
double& operator[](int index) {
return _arr[index] ;
}
const double& operator[](int index) const {
return _arr[index] ;
}
int size() const { return _size ; }
void resize(int newSize) {
// Allocate new array
double* newArr = new double[newSize] ;
// Copy elements
for (int i=0 ; i<_size ; i++) {
newArr[i] = _arr[i] ;
}
// Delete old array and install new one
if (_arr) {
delete[] _arr ;
}
_size = newSize ;
_arr = newArr ;
}
private:
int _size ;
double* _arr ;
} ;
#endif
#include "your-h-filename.h"
. #include "your-h-filename.h"
。 You will then be able to use defined classes, variables and functions defined in your .h file. You might want to read this: http://www.learncpp.com/cpp-tutorial/19-header-files/ 您可能需要阅读: http : //www.learncpp.com/cpp-tutorial/19-header-files/
In any .cpp file where you want to use this class, assuming "Array.h" is the relative path to the header file from your .cpp file, put the line: 在任何要使用此类的.cpp文件中,假设“Array.h”是.cpp文件中头文件的相对路径,请输入以下行:
#include "Array.h"
Near the top of the file, before any function or type declarations. 在任何函数或类型声明之前,靠近文件顶部。 This ensures that the code in your array file is treated as if it were written at that point in that .cpp file.
这可以确保将数组文件中的代码视为在该.cpp文件中的那一点写入。
As a further note, you usually want to split the definition of your class methods into a separate .cpp file (presumably Array.cpp). 另外,您通常希望将类方法的定义拆分为单独的.cpp文件(可能是Array.cpp)。 For example, for
resize
the definition in your header file should be changed to simply: 例如,要
resize
,头文件中的定义应该更改为:
void resize(int newSize);
and the full definition should be put in the .cpp file: 并且应将完整定义放在.cpp文件中:
void Array::resize(int newSize) {
// Allocate new array
double* newArr = new double[newSize] ;
// Copy elements
for (int i=0 ; i<_size ; i++) {
newArr[i] = _arr[i] ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.