gpt4 book ai didi

C++ 初学者 : calling default vs custom constructor

转载 作者:行者123 更新时间:2023-11-30 03:37:12 24 4
gpt4 key购买 nike

这里是初学者 - 但我不确定究竟要搜索什么(大概是常见的)问题。我正在开发一个程序,其中我有一个给定的类(字典)。我应该创建一个实现 Dictionary 的具体类(Word)。我应该提一下,我不会更改 Dictionary 中的任何内容。

在为Word制作头文件后,我在word.cpp中定义了所有内容。我不确定我这样做是否正确,但我让构造函数从给定文件中读取,并将信息存储在 Word 的公共(public)成员中。(我知道 vector 应该是私有(private)的,但我将其公开是为了找到当前问题的根源)

字典.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& file)”这一行,我得到了这个错误:'[错误] 没有匹配函数来调用 'Dictionary::Dictionary()'。

我被告知这是错误是由于“Word 的构造函数调用字典的”,但我仍然不太理解这个想法。我不是在尝试使用 Dictionary 的构造函数,而是 Word 的。如果有人有解决方案的想法,我也会感谢与导致此问题的原因相关的任何术语,我可以查找 - 我什至不确定如何命名问题。

最佳答案

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

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

似乎在这里描述得更好What are the rules for calling the superclass constructor?

关于C++ 初学者 : calling default vs custom constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40295714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com