带有数组成员变量的C++类构造函数

C++ Class Constructor With Array Member Variable

本文关键字:C++ 构造函数 变量 数组 组成员      更新时间:2023-10-16

我正在处理一个问题,我要构建一个具有40整数数组的类来计算40位数的加法和减法。

我已经写了下面的代码,但由于某种原因,它一直失败,并显示一条错误消息:

Implicit instantiation of undefined template 'std::_1::array<int, 40>'.

我不理解错误消息,也看不到代码有任何问题。你能帮忙吗?

此外,正如您所看到的,我使用的是memcpy函数,但当我只输入std::memcpy( hugeInteger, integer, sizeof( integer ) )时,它会吐出No viable conversion from 'std::array<int, 40>' to 'void'.据我所知,memcpy接受指针,而hugeInteger是指向数组第一个元素的指针。我理解不正确吗?

下面是标题:

#ifndef __Chapter_9__HugeInteger__
#define __Chapter_9__HugeInteger__
#include <stdio.h>
#include <vector>
class HugeInteger
{
public:
    explicit HugeInteger( bool = 1, std::array< int, 40 > = {} );
    void setHugeInteger( std::array< int, 40 > );
    void print();
private:
    bool checkHugeInteger( std::array< int, 40 > );
    std::array< int, 40 > hugeInteger = {};
    bool sign;
};
#endif /* defined(__Chapter_9__HugeInteger__) */

以下是cpp:

#include <array>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include "HugeInteger.h"
HugeInteger::HugeInteger( bool sign, std::array< int, 40 > integer )
: sign(sign)
{
    setHugeInteger( integer );
}
void HugeInteger::setHugeInteger( std::array< int, 40 > integer )
{
    if ( checkHugeInteger( integer ) )
        std::memcpy( hugeInteger, integer, sizeof( integer ) );
    else
        throw std::invalid_argument( "Single digit in the huge integer may not be negative ");
}
bool HugeInteger::checkHugeInteger( std::array< int, 40 > integer )
{
    bool tester = 1;
    for ( int i = int( integer.size() ) - 1; i >= 0; i-- )
    {
        if ( integer[i] < 0 )
        {
            tester = 0;
            break;
        }
    }
    return tester;
}
void HugeInteger::print()
{
    if ( sign < 0 )
        std::cout << "-";
    for( int i = int( hugeInteger.size() ) - 1; i >= 0; i-- )
        std::cout << hugeInteger[ i ];
}

我不明白你提到的错误,使用的是你的确切代码。但是,您的代码没有main函数。所以我认为还有另一个.cpp文件,您没有提到它包含main。如果是这样,则错误可能是因为该文件包含HugeInteger.h而没有执行#include <array>

HugeInteger.h应该自己做#include <array>,而不是依赖其他includer来做

要解决memcpy问题,请将memcpy线路替换为:

hugeInteger = integer;

std::array容器具有值语义,因此可以对其进行赋值

我还建议将接受array的函数更改为常量引用。这样可以在调用函数时避免不必要的复制。此外,checkHugeInteger函数可以是static,因为它不使用类的任何成员变量。