最近,我开始学习 C++,这是我的第一个 C++ 程序 - 但它不起作用。
错误信息:
No matching constructor for initialization of "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;};
关于C++ 没有匹配的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072662/