How do I pass arrays as parameters in a constructor? C ++
I am trying to create a constructor to call a class in which 4 arrays are passed as parameters. I've tried using *,&
the array itself; however, when I assign values in parameters to variables in the class, I get this error:
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]’
I would appreciate your help in finding my error and help me fix it. here is my code:
.h file
#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 file
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;
}
source to share
Raw arrays are not assignable and are usually difficult to handle. But you can put an array inside struct
and assign or initialize that. Essentially what std::array
.
eg. You can do
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 )
{}
};
But this still lacks a significant abstraction, so this is just a technical solution.
To improve the situation, consider what, for example, num_t
really is. Is this a phone number? Then model it as such.
We also consider the use of standard library containers std::vector
and arrays char
, std::string
.
source to share
In C / C ++, you cannot assign arrays by doing this->FROMNU=FROMNU;
, thus your method won't work and is half your error.
The other half is that you are trying to assign a pointer to an array. Even if you pass arrays to a function, they decay to pointers to the first element, regardless of what you say in the definition.
source to share