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

4

我正在尝试为类调用创建一个构造函数,其中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

C++文件

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;
}

如果您的编译器不支持C++11(或者您想使用替代方案),请将数组替换为std::arraystd::tr1::array(或者boost::array)。 - juanchopanza
数组并不等同于指针,尽管在许多情况下它们被降级为指针。对于您的用例,请考虑使用std::array而不是[]数组。 - us2012
8
你知道变量可以用小写字母吗? - Waleed Khan
3个回答

4

原始数组非可分配且通常难以处理。但是,您可以将数组放在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


1

在C++中,可以将原始数组作为参数传递。

考虑以下代码:

template<size_t array_size>
void f(char (&a)[array_size])
{
    size_t size_of_a = sizeof(a); // size_of_a is 8
}

int main()
{
    char a[8];
    f(a);
}

你在代码示例中使用了C++11的auto。有谁正常的头脑会使用那个而不是std::array呢? - us2012
1
这里不需要使用'auto'。我用明确的'size_t'替换了它。 - xmllmx

0
在C/C++中,你不能通过this->FROMNU=FROMNU;这样的方式来分配数组,因此你的方法不起作用,这是你错误的一半。
另一半错误是你试图将指针分配给数组。即使你将数组传递给函数,它们也会衰减为指向第一个元素的指针,而不管你在定义中说了什么。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接