继承和构造函数的问题

issues with inheritance and constructors

本文关键字:问题 构造函数 继承      更新时间:2023-10-16

在定义我的元素类时,我收到以下错误:

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 的 no 参数构造函数?

Word w("blah");

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

溶液:
要么为类 Dict 提供一个构造函数,它自己不带参数。

Dict()
{
} 


Element 中定义一个构造函数,该构造函数调用成员初始值设定项列表中的Dict的参数化构造函数之一。

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

通过声明自己的构造函数,你隐式地告诉编译器不要创建默认构造函数。如果你想使用类而不向Dict传递任何东西Element你还需要声明你自己的构造函数。

您收到第二个错误,因为编译器无法正确解析Element类,该类是Word的父类。同样,您还必须为 Element 声明构造函数Word以便类正常工作。

构造函数不是继承的,因此您需要 Element 的构造函数。 例如,

Element::Element(string f) : Dict(f) { }