数组模板和内置数组类型之间有区别吗

Is there a difference between array templates and built in array types?

本文关键字:数组 之间 有区别 类型 内置      更新时间:2023-10-16

我写了一个C++类,名为"Encrypt"。该类有几个函数,包括一个构造函数,它与数组数据成员交互,还接受数组作为参数。根据我正在读的书,最好使用数组模板并创建如下数组,而不是使用"内置"数组表示法。

我的书中说如何创建数组:

std::array <int, 8> digits;

我过去是如何创建阵列的:

int digits[8];

我将数组定义(我的第一个示例)包含为类的私有数据成员。我包含了一个构造函数,它接受一个数组,并使用该数组将数据存储在我的私有数据成员数组中。我的构造函数原型如下:

Encrypt(std::array <int, 8>);

问题是,我的老师提供了一个.cpp驱动程序文件,该文件将数组传递给我的构造函数。他宣布阵列的方式如下:

int Long[]={1,2,3,4,5,6,7,8};

因此,他使用了旧的"内置"数组表示法。他通过创建一个对象并提供数组基址来调用我的构造函数,如下所示:

Encrypt objName(Long);

当我试图编译我的程序时,我得到以下错误:

error C2664: 'Encrypt::Encrypt(const Encrypt &)' : cannot convert argument 1 from 'int[8]' to '_int64'

因此,我的猜测是,使用内置数组表示法创建的数组与从模板构建的数组不同。我不确定我是否遗漏了什么,因为我不明白为什么我的老师会使用一个与书中所说的不兼容的数组(这是一个在线课程,所以我从书中自学)。

这是我的"MCVE"请求-如果我遗漏了什么,请评论-我试图将我的类压缩为只重要的代码。

我的.h文件中的内容:

class Encrypt
{
public:
   Encrypt(long long int);             // class constructor to store last 4 digits of input
   Encrypt(std::array <int, 8>);       // second class constructor to store first 4 digits
private:
    std::array <int, 8> digits;  // data member array to hold digit inputs and encrypted data
};

我的.cpp类实现文件的内容(去掉了不相关的代码):

#include "Encrypt.h"
#include <iostream>
#include <array>
using namespace std;
// begin first constructor - accepts int input and stores last for digits
Encrypt::Encrypt(long long int input)  // constructor 1 - encrypts and stores data
{
   // removed code to store int argument into private data member array
} // end first constructor
// begin constructor 2 - accepts array and stores first 4 digits
Encrypt::Encrypt(array <int, 8> input)       
{
  // removed code that performs various operations on argument array and
  // private data member array
} // end of second constructor

调用我的构造函数的代码,由我的老师在.cpp"驱动程序"文件中提供:

#include "Encrypt.h" // include definition of class Encrypt
#include "Decrypt.h" // include definition of class Decrypt
#include <iostream>
#include <cstdlib>
using std::cin;
using std::cout;
using std::endl;
using std::atoi;

int main()
{  int Long[]={1,2,3,4,5,6,7,8};
int Negative[]={-8,7,6,5,4,3,2,1};
Encrypt eapp1(0), eapp2(40), eapp3(4560), eapp4(6145698),eapp5(-6), 
    eapp6(Long), eapp7(Negative); // create Encrypt objects
// more code to test program
return 0;
} // end of main

您不能自由交换C样式数组和<array>模板,它们是不同的东西。

但是您可以使用data()成员函数访问底层数组:

void Encrypt(int* a)
{
    // ....
}
int main(void)
{
    std::array <int, 8> digits;
    Encrypt(digits.data());
    int digits2[] = {1,2,3,4,5,6,7,8};
    Encrypt(digits2);
}

对于强类型,您可以使用以下内容:

class Encrypt
{
public:
    Encrypt(const std::array<int, 8>& a) : mArray(a) {}
#ifdef OPTION1
    Encrypt(const int (&a)[8]) : mArray({a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]}) {}
#else
    Encrypt(const int (&a)[8]) { std::copy(std::begin(a), std::end(a), std::begin(mArray)); }
#endif
private:
    std::array<int, 8> mArray;
};

(您可以看到为什么std::array比原始阵列更受欢迎)。