在定义我的 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/