【问题标题】:how to pass arrays as parameters in constructor? c++如何在构造函数中将数组作为参数传递? C++
【发布时间】:2013-02-18 00:50:23
【问题描述】:

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

【问题讨论】:

  • 如果您不支持 C++11,请将数组替换为 std::arraystd::tr1::array(或者,boost::array
  • 数组与指针不同,尽管在许多情况下它们被降级为指针。对于您的用例,请考虑使用 std::array 而不是 [] 数组。
  • 你知道变量可以是小写的,对吧?

标签: c++ arrays pointers parameters constructor


【解决方案1】:

原始数组是不可赋值的,通常难以处理。但是您可以在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

【讨论】:

    【解决方案2】:

    在 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。谁有正确的想法可以访问 C++11 并使用 that 而不是 std::array
    • 'auto' 在这里不是必需的。我用明确的“size_t”替换它
    【解决方案3】:

    在 C/C++ 中,您不能通过执行 this-&gt;FROMNU=FROMNU; 来分配数组,因此您的方法将不起作用,并且是您错误的一半。

    另一半是你试图分配一个指向数组的指针。即使您将数组传递给函数,它们也会衰减为指向第一个元素的指针,尽管您在定义中说了什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2015-08-02
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      相关资源
      最近更新 更多