gpt4 book ai didi

无法在 if 语句之外访问 c++ 结构

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:03:50 28 4
gpt4 key购买 nike

目标是让用户输入两部电影的一些电影信息。
然后两个函数输出电影数据
问题是当我尝试使用 if 语句之外的函数时,它们无法再被访问。

#include <iostream>
#include <string>
using namespace std;

struct MovieData // the stuct
{
string Title, // required varibles
Director;
int yearReleased,
runTime;

MovieData(string TITLE, string DIRECTOR, int YearReleased, int RunTime) // constructors
{
Title = TITLE;
Director = DIRECTOR;
yearReleased = YearReleased;
runTime = RunTime;
}
string getTitle() // getters
{ return Title; }
string getDirector()
{ return Director; }
int getYear()
{ return yearReleased; }
int getLength()
{ return runTime; }
};

void printMovie1(MovieData movieprint1) // fucntion that outputs movie 1
{
cout << "Title of movie " << movieprint1.getTitle() << endl;
cout << "Director is " << movieprint1.getDirector()<< endl;
cout << "Movie release year " << movieprint1.getYear()<< endl;
cout << "Movie length " << movieprint1.getLength() << endl;
}

void printMovie2(MovieData movieprint2) // function that outputs movie 2
{
cout << "Title of movie " << movieprint2.getTitle() << endl;
cout << "Director is " << movieprint2.getDirector() << endl;
cout << "Movie release year " << movieprint2.getYear() << endl;
cout << "Movie length " << movieprint2.getLength() << endl;
}

int main()
{
string Title, // local varibles
Director;
int yearReleased,
runTime;

for (int i = 0; i < 2; i++) // forward loop to enter movie info
{
cout << "Please enter the movie " << (i + 1) << " title ";
getline(cin, Title);

cout << "Now the director ";
getline(cin, Director);

cout << "What year was " << Title << " releasted ";
cin >> yearReleased;

cout << "Lastly the length ";
cin >> runTime;
cin.ignore();

if (i == 0)
{
MovieData movie1(Title, Director, yearReleased, runTime);
// I know function works when placed here
// printMovie1(movie1);
}
else if (i == 1)
{
MovieData movie2(Title, Director, yearReleased, runTime);
// I know function works when placed here
// printMovie2(movie2);
}
}
// these functions now dont work
enter code hereprintMovie1(movie1);
printMovie2(movie2);
return 0;
}

最佳答案

您的 MovieData 仅存在于括号范围内。一旦退出外部范围,就无法再访问它。您可以修复它,在范围之外声明您的变量。

    MovieData  movie; //default construction
if (i == 0)
{
movie = MovieData(Title, Director, yearReleased, runTime);
// I know function works when placed here
// printMovie1(movie1);
}
else if (i == 1)
{
movie= MovieData(Title, Director, yearReleased, runTime);
// I know function works when placed here
// printMovie2(movie2);

}
//you can now use movie

关于无法在 if 语句之外访问 c++ 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29843652/

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