C ++没有匹配的构造函数

时间:2013-04-18 00:44:39

标签: c++

最近,我开始学习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();
        }
    };

2 个答案:

答案 0 :(得分:3)

我的猜测是你试图通过使用默认构造函数来实例化你的Document类,但是,你没有在代码中定义默认构造函数。 您只在公共部分中定义了两个重载版本的构造函数:

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;};

答案 1 :(得分:2)

问题在于您未向我们展示的代码,您尝试创建此类型的对象。您需要使用其中一个已定义的构造函数:

Document d1(docId); 
Document d2(docId, lanId);

我的猜测是你试图默认构建一个:

Document d;

该类没有(也可能不应该)具有默认构造函数Document(),因此这不起作用。