[英]C++ Class Constructor With Array Member Variable
我正在研究一个问题,其中我要构建一个具有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>
,而不是依靠其他includeers来执行。
要解决memcpy
问题,请将memcpy
行替换为:
hugeInteger = integer;
std::array
容器具有值语义,因此您可以对其进行分配。
我还建议更改您的接受array
函数,以通过const引用将其接收。 这样可以避免在调用函数时产生不必要的复制。 同样,由于checkHugeInteger
函数不使用该类的任何成员变量,因此它可能是static
的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.