gpt4 book ai didi

c++ - 没有空构造函数编译失败

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:40 24 4
gpt4 key购买 nike

我是 C++ 的新手,并试图准确理解我的代码发生了什么。

这些类都在它们自己的头文件中定义。代码如下。

队列:

template<class T> class Queue
{
public:
Queue(unsigned int size)
{
_buffer = new T[size]; //need to make sure size is a power of 2
_write = 0;
_read = 0;
_capacity = size;
}

/* other members ... */

private:
unsigned int _capacity;
unsigned int _read;
unsigned int _write;
T *_buffer;
};

连续剧:

template<class T> class Queue;
template<class T> class Serial
{
public:
Serial(unsigned int buffer_size)
{
_queue = Queue<T>(buffer_size); //<---here is the problem
}
private:
Queue<T> _queue;
};

当我尝试像这样创建一个 Serial 实例时:

Serial<unsigned char> s = Serial<unsigned char>(123);

编译器提示没有参数为零的 Queue 构造函数,至少我认为这是错误的意思:

In instantiation of 'Serial<T>::Serial(unsigned int) [with T = unsigned char]':

no matching function for call to 'Queue<unsigned char>::Queue()'

ambiguous overload for 'operator=' in '((Serial<unsigned char>*)this)->Serial<unsigned char>::_queue = (operator new(16u), (((Queue<unsigned char>*)<anonymous>)->Queue<T>::Queue<unsigned char>(buffer_size), ((Queue<unsigned char>*)<anonymous>)))' (operand types are 'Queue<unsigned char>' and 'Queue<unsigned char>*')

invalid user-defined conversion from 'Queue<unsigned char>*' to 'const Queue<unsigned char>&' [-fpermissive]

invalid user-defined conversion from 'Queue<unsigned char>*' to 'Queue<unsigned char>&&' [-fpermissive]

conversion to non-const reference type 'class Queue<unsigned char>&&' from rvalue of type 'Queue<unsigned char>' [-fpermissive]

当我向 Queue 添加一个空的构造函数时,它编译没有问题。当我单步调试调试器时,我看到它进入带有参数的构造函数,而不是空参数。

为什么会这样?

最佳答案

Serial(unsigned int buffer_size)缺乏member init list ,因此 _queue必须首先使用默认构造函数创建,然后为其分配一个值 ( Queue<T>(buffer_size) )。

这个:

Serial(unsigned int buffer_size) : _queue(buffer_size) {}

将使用 Queue(unsigned int)构造函数代替,并且在没有默认构造函数的情况下也能工作。

关于c++ - 没有空构造函数编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47851004/

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