没有匹配的构造函数

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(),所以这不起作用。