gpt4 book ai didi

c++ - 如何在构造函数中将数组作为参数传递? C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:32 25 4
gpt4 key购买 nike

我正在尝试为类调用创建一个构造函数,其中将 4 个数组作为参数传递。我试过使用 *,& 和数组本身;但是,当我将参数中的值分配给类中的变量时,出现此错误:

 call.cpp: In constructor ‘call::call(int*, int*, char*, char*)’:
call.cpp:4:15: error: incompatible types in assignment of ‘int*’ to ‘int [8]’
call.cpp:5:16: error: incompatible types in assignment of ‘int*’ to ‘int [8]’
call.cpp:6:16: error: incompatible types in assignment of ‘char*’ to ‘char [14]’
call.cpp:7:16: error: incompatible types in assignment of ‘char*’ to ‘char [14]’

非常感谢您帮助我找出错误并帮助我改正错误。这是我的代码:

.h文件

#ifndef call_h
#define call_h
class call{
private:
int FROMNU[8];
int DESTNUM[8];
char INITIME[14];
char ENDTIME[14];

public:
call(int *,int *,char *,char *);
};
#endif

.cpp文件

call:: call(int FROMNU[8],int DESTNUM[8],char INITIME[14],char ENDTIME[14]){
this->FROMNU=FROMNU;
this->DESTNUM=DESTNUM;
this->INITIME=INITIME;
this->ENDTIME=ENDTIME;
}

最佳答案

原始数组不可赋值,通常难以处理。但是您可以将一个数组放在 struct 中,然后对其进行分配或初始化。 std::array 本质上就是这样。

例如你可以做到

typedef std::array<int, 8>   num_t;
typedef std::array<char, 14> time_t;

class call_t
{
private:
num_t from_;
num_t dest_;
time_t init_;
time_t end_;

public:
call_t(
num_t const& from,
num_t const& dest,
time_t const& init,
time_t const& end
)
: from_t( from ), dest_( dest ), init_( init ), end_( end )
{}
};

但这仍然缺乏一些基本的抽象,因此它只是一个技术解决方案。

要改进事物,请考虑什么,例如num_t 确实是。也许是电话号码?然后这样建模。

还考虑使用标准库容器 std::vector,对于 char 的数组,std::string

关于c++ - 如何在构造函数中将数组作为参数传递? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14927956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com