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

标签 c++

最近,我开始学习 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/

相关文章:

c++ - 直接在 foreach 循环中强制转换

c++ - n 作为参数传递给函数后为 0,这里似乎有什么问题?

c++ - 如何正确公开基础模板类型以用作类型

c++ - 与 Visual Studio 不同版本的链接错误

c++ - 在 Qt QProcess 中运行 sudo 命令

c++ - 对左值和右值的可分配引用

c++ - 使用 COM 互操作时,为什么后期绑定(bind)会修复 "ByRef value type parameter cannot be null"错误?

c++ - 如何在 C++ 中为我自己的类编写 gtest unittest

c++ - 如何比较 CUDA C++ 中的 char 数组?

c++ - 正则表达式迭代器在 Cpp 中不起作用