【发布时间】:2017-01-18 05:22:50
【问题描述】:
我正在处理的最大问题是在我的 main.cpp 文件中,但是我发布了我的 video.h 文件和 video.cpp 文件以防万一。
我很难理解读取输入然后创建对象的概念。
我有一个 Video 类,其中包含创建对象所需的成员函数。我的课很好。在我的主要内容中,我希望能够在创建对象之前读取输入,而不是创建对象然后初始化变量。
视频.h
#ifndef VIDEO_H
#define VIDEO_H
#include<iostream>
#include<string>
using namespace std;
class Video{
public:
// constructor works fine
Video(string name, string link, string comment,
double rating, int stars);
void print();
// member variables
private:
string m_name;
string m_link;
string m_comment;
double m_rating;
int m_stars;
};
#endif
视频.cpp
#include<iostream>
#include "video.h"
using namespace std;
Video :: Video (string name, string link, string comment,
double rating, int stars){
m_name = name;
m_link = link;
m_comment = comment;
m_rating = rating;
m_stars = stars;
}
void Video :: print (){
cout << m_name << ", " << m_link << ", " << m_comment << ", " <<
m_rating << ", ";
for(int count = 0; count < m_stars; ++count){
cout << "*";
//cout << endl;
}
cout << endl;
//<< " , " << m_stars << endl;
}
main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "video.h"
int main()
/* My program can create objects and initialize the string variables
if the data is hard-coded when the object is created however I want
read data using cin and a while loop then create an object.
Video video1("Title One", "www.youtube.com/one",
"Comment ONE", 1.1, 1);
Video video2("Title Two", "www.youtube.com/two",
"Comment TWO", 2.2, 2);
video1.print();
video2.print();
*/
{
while (Video >> cin) { //I want to use a while loop here
/* The program needs to read these getlines
and other variables in order to store names or comments
that have spaces */
getline(cin, name); // user enters the name then presses "enter"
getline(cin, link); // user enters the link then presses "enter"
getline(cin, comment); // user enters the comment then presses "enter"
double rating; // user enters the rating then presses "enter"
int stars; // user enters the amount of stars then presses "enter"
Video video_one; /* Once the user enters data for all five members a new object is created */
}
}
【问题讨论】:
-
呃,Video 是一种运行时类型,所以不可能编译。您需要在重载
>>运算符的类型上创建一个朋友。
标签: c++ class object while-loop cin