c++ - 继承和构造函数的问题

标签 c++ inheritance

在定义我的 Element 类时出现以下错误:

no matching function for call to ‘Dict::Dict()’ word1.cpp:23:
    note: candidates are: Dict::Dict(std::string) word1.cpp:10:
    note: Dict::Dict(const Dict&)

我没有调用任何东西,我只是让 Element 继承自 Dict。这里有什么问题?

另一个错误出现在我的 Word 类构造函数中,我得到以下信息:

In constructor ‘Word::Word(std::string)’: word1.cpp:71:
    note: synthesized method ‘Element::Element()’ first required here

此时我真的很沮丧,因为我觉得一切都还好。

#include <iostream>
#include <vector>
#include <sstream>
#include <string.h>
#include <fstream>

using namespace std;

class Dict {
   public:
    string line;
    int wordcount;
    string word;
    vector <string> words;

    Dict(string f) {
        ifstream in(f.c_str());
        if (in) {
            while (in >> word) {
                words.push_back(word);
            }
        }
        else cout << "ERROR couldn't open file" << endl;
        in.close();
    }
};

class Element: public Dict { //Error #1 here 
    //Don't need a constructor
    public:
      virtual void complete(const Dict &d) = 0;
      //virtual void check(const Dict &d) = 0;
      //virtual void show() const = 0;
};

class Word: public Element{
    public:
      string temp;
      Word(string s){ // Error #2 here
          temp = s;
      }
      void complete(const Dict &d){cout << d.words[0];}
};

int main()
{
    Dict mark("test.txt"); //Store words of test.txt into vector
    string str = "blah"; //Going to search str against test.txt
    Word w("blah"); //Default constructor of Word would set temp = "blah"
    return 0;
}

最佳答案

如果您自己为类 Dict 定义任何构造函数,则需要提供不带参数的构造函数。

从哪里调用Dict 的无参数构造函数?

Word w("blah");

通过调用 Word(string s) 创建一个 Word 对象。但是,由于 Word 派生自 Element,而 Element 又派生自 Dict,因此它们的默认构造函数(不带参数)也将被调用.而且您没有为 Dict 定义无参数构造函数所以错误。

解决方案:
要么为类 Dict 提供构造函数,它自己不带参数。

Dict()
{
} 

或者
Element 中定义一个构造函数,它调用 Member Initializer List 中 Dict 的参数化构造函数之一。

Element():Dict("Dummystring")
{
} 

关于c++ - 继承和构造函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109899/

相关文章:

java - Scala:继承接口(interface)成员初始化

java - 继承和静态嵌套 Java 类

C++如何使用fstream读取带空格的制表符分隔文件

c++ - 为什么类级别的 typedef 不从模板继承?

c++ - 如何找到使用 C++ 在注册表中注册的 DLL 的绝对路径?

c++ - 在 push_back() 之前保留非空 std::vector 的正确方法

具有继承性的 Java Builder 模式

c++ - 如何从 std::runtime_error 继承?

C++ 转换为基数和 "overwriting"vptr 问题

c++ - 如何在没有 "&"或 "*"的情况下为调用的方法提供正确的参数?