我正在尝试编写一个程序,当用户输入电影的关键字时,程序会在标题中搜索它并返回结果。我被困在如何尝试这样做。我不断收到有关在header类中没有默认构造函数的错误。我不知道如何解决这个问题。
这是标题类
// Movies.h
#ifndef MOVIES_H
#define MOVIES_H
#include "Movie.h" // include Movie class definition
#include <string>
using namespace std;
class Movies {
// data is private by default
static const int MAX_MOVIES = 1000;
Movie movies[MAX_MOVIES];
int movieCnt;
public:
Movies(string);
void Test(string);
const Movie getMovie(int);
private:
void loadMovies(string);
string myToLower(string);
};
#endif
这是标题
的cpp文件// Movies.cpp
#include "Movie.h" // include Movie class definition
#include "Movies.h" // include Movies class definition
#include <fstream>
using namespace std;
Movies::Movies(string fn){loadMovies(fn);}
const Movie Movies::getMovie(int mc) {
return movies[mc-1];
}
void Movies::loadMovies(string fn) {
ifstream iS(fn);
string s;
getline(iS, s); // skip heading
getline(iS, s);
movieCnt=0;
while(!iS.eof()) {
movies[movieCnt++] = Movie(s);
getline(iS, s);
}
iS.close();
}
void Movies::Test(string key)
{
Movies[1];
}
string Movies::myToLower(string s) {
int n = s.length();
string t(s);
for(int i=0;i<n;i++)
t[i] = tolower(s[i]);
return t;
}
这是我的主要功能
// MovieInfoApp.cpp
#include "Movie.h" // include Movie class definition
#include "Movies.h" // include Movies class definition
#include <iostream>
#include <string>
using namespace std;
void main() {
Movies movies("Box Office Mojo.txt");
string answer, key;
bool set = false;
int movieCode, ant;
cout<< "Would you like to start the Movie search?";
cin>> answer;
while (answer =="y" ||answer =="Y")
{
cout<< "would you like to enter a movie name or a movie number? (press 1 for movie name press 2 for number";
cin>>ant;
if (ant = 2)
{
cout << "Please enter the movie number: ";
cin >> movieCode;
Movie m = movies.getMovie(movieCode);
if(m.getTitle().length() > 0)
{
cout << m.toString() << "\n";
}
else
{
cout << "\n Movie not found!\n\n" << endl;
}
}
else if (ant =1)
{
cout << "Please enter a keyword or title of the movie: ";
cin >> key;
Movies tester; // No default constructor error over here
tester.Test(key);
}
else
{
cout<< "invalid entry please try again";
}
cout<< "Would you like to continute the Movie search?";
cin>> answer;
}
}
答案 0 :(得分:3)
错误很明显,因为它可以得到 - 你没有默认的构造函数。 FYI,默认构造函数是可以不带任何参数调用的构造函数。
Movies tester;
将尝试调用默认构造函数。您定义了一个非默认值 - Movies(string);
,因此编译器不再为您生成默认值。
答案 1 :(得分:3)
您正尝试使用默认构造函数声明tester
,并且Movie movies[1000]
使用默认构造函数,但您的类没有默认构造函数。
您需要为tester
提供参数或定义默认构造函数。
对于数组,即使您确实定义了一个默认构造函数以使其工作,我建议不要使用将直接存储在对象中的数组,因为那时您的对象非常庞大(并且可能会让您意外地发生堆栈溢出)。使用std::vector
,这将解决多个问题。