无法在main中调用struct函数

时间:2018-11-24 04:06:39

标签: c++ struct

因此,由于某种原因,我的代码无法编译,并且不断遇到此错误:

  

无法将'(Movie *)(&myMovie)'从'Movie *'转换为'Movie'**

不知道这是什么意思,如果有人可以告诉我我的代码有什么问题,也很感激,对结构很陌生,对于任何愚蠢的错误都表示歉意。

我想输出用户在提示输入电影详细信息问题时输入的内容,但正如我提到的那样。

谢谢。 这是我的代码:

#include <iostream>
#include <cstring>
#include <iomanip>
#include <climits>
#include <cstdlib>

using namespace std;

const int MAX = 256;
const int MAXNUM = 10;
const int MINNUM = 1;

typedef char  Word[MAX];

//define a struct for a Movie
struct Movie{
  Word title;
  Word Director;
  float length;
};


// prompts user for number between min and max, and returns valid input
int getIntInRange(int min, int max);



//prompts user for a positive float, and returns valid value
float getPositiveFloat();


//prompts user to enter all the values in a movie and returns the movie

//implement these two functions

Movie getMovieFromUser();
//outputs a single movie

void outputMovie(Movie m);



//describe program to user
void displayOverview();


int main(){

//output overview of program

//prompt user to enter their favourite movie

//use the getMovieFromUser() function to get the movie and store it in a variable

//output the movie using the outputMovie function


  cout << endl;

  Movie myMovie[MAXNUM];
  getMovieFromUser(????);
  outputMovie(????);


return 0;
}

Movie getMovieFromUser(){

    Movie myMovie;
    //prompt user to enter title, and save it
    //prompt user to enter director and save it
    //prompt user for length, and save it

    Word buffer;
    cout << "Please enter your favourite movie \n";
    cout << "Title: ";
    cin.getline(buffer, MAX);
    strcpy(m.title, buffer);
    cout << "Director: ";
    cin.getline(buffer, MAX);
    strcpy(m.Director, buffer);
    m.length = getPositiveFloat();


    return myMovie;
}


void outputMovie(Movie m){
//output the contents of this movie
    cout << "Title: " << m.title << endl;
    cout << "Director: " << m.Director << endl;
    cout << "Length (minutes): " << m.length << endl;
}

1 个答案:

答案 0 :(得分:3)

您的代码与自己不同。你有:

Movie getMovieFromUser();

但是后来:

Movie getMovieFromUser(Movie &m){

第一个似乎更有意义。名为getMovieFromUser的函数可以采用其填充的参考参数或返回值。返回值似乎更有意义。修复后,此代码应编译:

Movie myMovie[MAXNUM];
myMovie[0] = getMovieFromUser();
outputMovie(myMovie[0]);

您需要摆脱Movie &m中的getMovieFromUser参数。只需在本地创建一个即可(就像您已经做的那样)。我建议将其命名为m而不是myMovie,因为它可能会混淆具有两个具有相同名称的变量。

将它们放在一起:

Movie getMovieFromUser(){

    Movie m;
    //prompt user to enter title, and save it
    //prompt user to enter director and save it
    //prompt user for length, and save it

    Word buffer;
    cout << "Please enter your favourite movie \n";
    cout << "Title: ";
    cin.getline(buffer, MAX);
    strcpy(m.title, buffer);
    cout << "Director: ";
    cin.getline(buffer, MAX);
    strcpy(m.Director, buffer);
    m.length = getPositiveFloat();
    return m;
}