在构造函数或init函数中创建对象 [英] Creating an object in the constructor or an init function
本文介绍了在构造函数或init函数中创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经定义了类似这样的类:
class CircularBuffer {
private:
struct entry {
uint64_t key;
int nextPtr;
int prevPtr;
int delta;
};
int head,tail,limit,degree;
entry * en;
public:
CircularBuffer(int a,int b)
{
limit = a;
head = 0;
tail = limit -1;
degree = b;
en = new entry [limit];
for(int i = 0; i en [i] .key = 0;
en [i] .delta = 0;
en [i] .nextPtr = 0;
en [i] .prevPtr = 0;
}
};
〜CircularBuffer(){delete [] en; }
};
在另一个文件中,我包含了这个类(头文件)
#includecircular.h
class foo {
CircularBuffer cb;
foo(){} //错误LINE
void initialize(){
cb = new CircularBuffer(10,2);
}
};
但是,这里有错误:
错误:没有匹配的函数调用'CircularBuffer :: CircularBuffer()'
注意:候选人是:CircularBuffer :: CircularBuffer(int,int)
注意: CircularBuffer :: CircularBuffer(const CircularBuffer&)
它强迫我这样做:
#includecircular.h
class foo {
CircularBuffer cb;
foo()
:cb(CircularBuffer(10,2))
{}
void initialize(){}
};
但是我不想第二次实现。我想要第一个。
解决方案
可以添加默认构造函数
CircularBuffer()
pre>
{
//将a和b设置为默认值
}
I have defined a class like this:
class CircularBuffer { private: struct entry { uint64_t key; int nextPtr; int prevPtr; int delta; }; int head, tail, limit, degree; entry *en; public: CircularBuffer(int a, int b) { limit = a; head = 0; tail = limit -1; degree = b; en = new entry[ limit ]; for (int i=0; i<limit; i++) { en[i].key = 0; en[i].delta = 0; en[i].nextPtr = 0; en[i].prevPtr = 0; } }; ~CircularBuffer() { delete [] en; } };
And in another file I have included this class (the header file)
#include "circular.h" class foo { CircularBuffer cb; foo() {} //ERROR LINE void initialize() { cb = new CircularBuffer(10, 2); } };
However this has error which says:
error: no matching function for call to ‘CircularBuffer::CircularBuffer()’ note: candidates are: CircularBuffer::CircularBuffer(int, int) note: CircularBuffer::CircularBuffer(const CircularBuffer&)
and it forces me to do like this:
#include "circular.h" class foo { CircularBuffer cb; foo() : cb( CircularBuffer(10, 2) ) {} void initialize() {} };
However I don't want the second implementation. I want the first one. How can I fix that?
解决方案You can add a default constructor
CircularBuffer() { // set a and b to default values }
这篇关于在构造函数或init函数中创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文