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

C++ Beginner : calling default vs custom constructor

本文关键字:构造函数 vs 自定义 默认 调用 初学者 c++      更新时间:2023-10-16

这里是初学者-但我不确定究竟要搜索这个(大概是常见的)问题。我正在做一个程序,我有一个给定的类(字典)。我应该做一个具体的类(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) 
{ 
   ... 
}

似乎在这里更好地描述调用超类构造函数的规则是什么?