C ++初学者:调用默认vs自定义构造函数

时间:2016-10-27 23:24:48

标签: c++

初学者 - 但我不确定究竟要搜索这个(可能是常见的)问题。 我正在开发一个程序,我有一个给定的类(Dictionary)。我应该创建一个实现Dictionary的具体类(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&amp; file)”行上,我收到此错误:'[Error]没有匹配函数来调用'Dictionary :: Dictionary()'。

我被告知这是错误是由于“Word的构造函数调用字典”,但我仍然不太了解这个想法。我不是试图使用Dictionary的构造函数,而是使用Word的。 如果有人有解决方案的想法,我也会感谢任何与导致这个问题有关的条款,我可以查询 - 我甚至不确定如何标题。

1 个答案:

答案 0 :(得分:2)

您的子类应该调用父构造函数,因为父对象是在子对象之前构造的。所以你应该写一些类似的东西:

Word::Word(isteam& file) : Dictionary(file) 
{ 
   ... 
}

这里有更好的描述What are the rules for calling the superclass constructor?

相关问题