没有匹配的构造函数
C++ No matching constructor
本文关键字:构造函数 更新时间:2023-10-16
最近,我开始学习c++,这是我的第一个c++程序——但是它不起作用。
错误信息:
初始化"Document"没有匹配的构造函数。
我使用的IDE是Xcode。
class Document {
private:
int doc_id;
int lan_id;
std::vector<int>::size_type n_total;
std::vector<int> words;
std::vector<int> counts;
inline int doc_type(){return (counts.empty() && !words.empty())? 1:0;};
public:
Document(int docId)
{
doc_id = docId;
n_total = 0;
}
Document(int docId, int lanId)
{
lan_id = lanId;
doc_id = docId;
n_total = 0;
}
inline void add(int word, int count)
{
words.push_back(word);
counts.push_back(count);
}
inline void add(int word) { words.push_back(word);}
inline int word(int i) { return words[i]; }
inline int count() { return counts[1];};
inline std::vector<int>::size_type size() { return n_total;};
inline void setSize(std::vector<int>::size_type total){ n_total = total;};
inline std::vector<int>::size_type types() { return words.size();}
~ Document()
{
words.clear();
counts.clear();
}
};
我的猜测是,您正在尝试通过使用默认构造函数实例化您的Document
类,但是,您没有在代码中定义默认构造函数。您只在public节中定义了构造函数的两个重载版本:
Document(int docId, int lanId)
和
Document(int docId)
如果你像下面这样实例化你的对象
Document d;
会给你编译错误,因为编译器找不到默认构造函数来完成对象的创建。同时,您已经定义了自己的构造函数,因此编译器不会为您生成默认构造函数。
此外,有几个地方放置了多余的分号,这很容易出错,不应该在那里。
例如: inline int doc_type(){return (counts.empty() && !words.empty())? 1:0;};
//^^^^
inline int count() { return counts[1];};
inline std::vector<int>::size_type size() { return n_total;};
inline void setSize(std::vector<int>::size_type total){ n_total = total;};
问题出在您没有向我们展示的代码中,您试图在其中创建这种类型的对象。您需要使用定义的构造函数之一:
Document d1(docId);
Document d2(docId, lanId);
我猜你是在尝试默认构造一个:
Document d;
这个类没有(可能也不应该)有默认构造函数Document()
,所以这不起作用。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为