c++初学者:调用默认构造函数vs自定义构造函数
C++ Beginner : calling default vs custom constructor
这里是初学者-但我不确定究竟要搜索这个(大概是常见的)问题。我正在做一个程序,我有一个给定的类(字典)。我应该做一个具体的类(Word)实现字典。我应该提一下,我不会改变字典里的任何东西。
在为Word制作头文件后,我在Word .cpp中定义了所有内容。我不确定这样做是否正确,但是我让构造函数从给定的文件中读取信息,并将信息存储在Word的公共成员中。(我知道向量应该是私有的,但我把它公开是为了找到当前问题的根源)
dictionary.h
#ifndef __DICTIONARY_H__
#define __DICTIONARY_H__
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class Dictionary
{
public:
Dictionary(istream&);
virtual int search(string keyword, size_t prefix_length)=0;
};
#endif /* __DICTIONARY_H__ */
word.h
#ifndef __WORD_H__
#define __WORD_H__
#include "dictionary.h"
class Word : public Dictionary{
public:
vector<string> dictionary_words;
vector<string> source_file_words;
Word(istream &file);
int search(string keyword, size_t prefix_length);
void permutation_search(string keyword, string& prefix, ofstream& fout, int& prefix_length);
};
#endif /* __WORD_H__*/
word.cpp
#include "word.h"
Word(istream& file) : Dictionary(istream& file)
{
string temp;
while (file >> temp)
{
getline(file,temp);
dictionary_words.push_back(temp);
}
}
在Word .cpp中,在"Word::Word(istream&,我得到这个错误:'[错误]没有匹配的函数调用'Dictionary::Dictionary()'.
我被告知这是错误是由于"Word的构造函数调用字典的",但我仍然不太理解这个想法。我不是试图使用字典的构造函数,而是Word的。如果有人有一个解决方案的想法,我也会感谢任何与导致这个问题的原因相关的术语,我可以查找-我甚至不确定如何命名这个问题。
您的子类应该调用父构造函数,因为父对象是在子对象之前构造的。所以你应该这样写:
Word::Word(isteam& file) : Dictionary(file)
{
...
}
似乎在这里更好地描述调用超类构造函数的规则是什么?
相关文章:
- 将参数传递给 c++ 构造函数时出现 VS 编译错误
- C++ std::stringstream 运算符<< vs (构造函数)
- VS为我提供了对构造函数的另一个解决方案,但我想知道为什么我的工作不起作用
- 在 C++ vs Java 中从构造函数调用被覆盖的方法
- 为什么在 VS 中需要复制构造函数来packaged_task
- 从成员构造函数(Brace Initializer vs Initializer列表)抛出异常
- C 构造函数:使用this_class(GCC vs Visualc)
- 多映射插入键类型信息 std::make_pair vs std::p air 构造函数
- cppcheck vs clang整洁:显式构造函数initializer_list
- 复制构造函数 VS 构造函数,并将类指针作为参数
- Linux vs Windows std::map 赋值构造函数(为什么会有这样的区别?)
- 关于带有复制构造函数的vs/g++
- 使用 VS 2012 在构造函数中的树节点中初始化数组
- 直接初始化字段vs默认构造函数中的初始化列表
- 构造函数依赖注入:unique_ptr + move vs shared_ptr
- c++初学者:调用默认构造函数vs自定义构造函数
- 构造函数初始化列表vs昂贵操作
- 移动构造函数和前增量vs后增量
- 无法引用默认构造函数 - 它是 VS 中已删除的函数
- 单例保护构造函数vs私有构造函数