继承和构造函数的问题
issues with inheritance and constructors
在定义我的元素类时,我收到以下错误:
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) { }
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- constexpr构造函数需要常量成员函数时出现问题
- 有关 c++ 构造函数的问题
- 关于复制构造函数的一个棘手问题
- 复制构造函数隐式转换问题
- 构造函数 (C++) 中的 char 指针参数存在问题
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 关于 std::bitset 构造函数的几个问题?
- 构造函数和 G++ 编译配方的问题
- 在 boost::variant 中类 holden 的复制构造函数存在问题
- C++ 关于两个类构造函数的问题
- 在构造函数 c++ 中初始化属性时出现问题
- 空构造函数和值传递问题
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- 复制和赋值构造函数的问题
- 变分模板递归构造函数问题
- C++中用户定义的构造函数出现问题
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- C++的抽象类继承和构造函数的问题
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?