2011-11-13 48 views
0

在定义我的元素类,我得到以下错误:问题与继承和构造

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&) 

我没有要求任何东西,我只是让元素从字典继承。这里有什么问题?

其他错误是我的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; 
} 

回答

5

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

从没有无参数的构造函数用于Dict被调用在哪里?

Word w("blah"); 

通过调用Word(string s)创建一个Word对象。但是,因为Word源自Element,而Element又来自Dict,所以它们的缺省构造函数也将被调用,它们将不会调用参数。而且你没有为Dict定义一个没有参数的构造函数所以这个错误。

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

Dict() 
{ 
} 

或者
定义Element构造它调用的Dict在成员初始化列表的参数构造函数之一。

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

通过声明你自己的构造函数,你隐式地告诉编译器不要创建默认构造函数。如果您想使用Element类而不传入任何内容到Dict,那么您还需要声明自己的构造函数。

由于编译器无法正确解析的父类Element,您正在接收第二个错误。再次,您还需要声明Element的构造函数,以便Word类能够正常工作。

+0

这不仅仅是一个复制构造函数(他没有提供)。它提供了*任何*构造函数,用于防止创建默认构造函数。 –

0

构造函数不是继承的,所以你需要Element的构造函数。例如,

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