带有数组成员变量的C++类构造函数
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>
,而不是依赖其他includer来做
要解决memcpy
问题,请将memcpy
线路替换为:
hugeInteger = integer;
std::array
容器具有值语义,因此可以对其进行赋值
我还建议将接受array
的函数更改为常量引用。这样可以在调用函数时避免不必要的复制。此外,checkHugeInteger
函数可以是static
,因为它不使用类的任何成员变量。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为