【问题标题】:C++ Difficulty with class objects类对象的 C++ 困难
【发布时间】:2020-11-24 22:27:54
【问题描述】:

我是 C++ 的新手,对整体编程也很陌生。我正在使用 C++ 进行课堂作业,以管理有 10 张 DVD 的 DVD 商店。目标是通过使用抽象数据类型并通过从文本文件中提取使用包含 10 个 DVD 实例的数组来打印出每张 DVD 的信息。

到目前为止,我已经能够导入文本文件,逐行读取,将每一行拆分为 4 个字符串(标题、流派、评级、描述)。现在我正在尝试将它连接到我所做的类函数,以将每个字符串实际连接到 DVD 类 - 标题、流派、评级、描述。

我不太了解类,并已尽力在我的文本、C++ 入门和在线阅读它们,但它们还没有完全点击。

我是否创建了 10 个类实例,并将每个类实例设置为等于我的每个字符串?

最好显示一些代码:

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

class Dvd   {
public:
    string title, genre, rating, description;
    string print(void)  {
        return (title + genre + rating + description + "\n"); 
    } //Dont even know if this is right... My best first attempt at class creation...
};

int main()  { 
    Dvd one, two, three, four, five, six, seven, eight, nine, ten; //initialize class objects
    string line, word, templist[10];
    
    ifstream in("dvd_list.txt");
    for(int i = 0; i < 10; i++) {
        getline(in, line);
        templist[i] = line; //read the file into a line

        string components;
        istringstream temp(line); 

        while(getline(temp, components, ';'))   { // Splits line into strings
            for(int k = 0; k < 4; k++)  {
                //wanting to bind strings to class objects here
            }   //My thought was to use if(k = 0), --> one.title = component
        }       // if(k = 1) --> one.genre etc....
    }
}

因此,在这一点上,我的想法是使用最后一个 for 循环 (K) 将类与各个组件字符串联系起来。我试图了解如何将类对象实际绑定到字符串。我认为代码最终会是这样的:

one.title = ....
one.genre = ....
one.rating = ....

但我想知道是否有更好的方法来做到这一点(for循环或其他东西)?或者只是手动把它全部写出来,直到我到达那里(这似乎是错误的,但我不知道如何从这里变得高效)。

最后:我也知道using namespace.... 不是很好的做法,但是我正在阅读的书和课程鼓励这一点,直到本节进行到一半,并且正在过渡到 std::.... 但现在,在转变这种心态之前,我需要专注于理解课程并让它发挥作用。 感谢您的帮助!

【问题讨论】:

  • 在您的print 函数中,您是否忘记了字段之间的分隔符?您的文本将被连接起来,没有空格。
  • 老实说,还没有到达那里。我只是尝试一次做一步,而 print() 我将在接近尾声时进行更多调整。我会记住这一点!谢谢!

标签: c++ class


【解决方案1】:

您想要:

Dvd myDvds[10];

std::vector<Dvd> dvdVect(10);

然后您可以使用myDvds[i]dvdVect[i] 访问它们。

【讨论】:

  • std::vector&lt;Dvd&gt; dvdVect(10); 我的钱。
  • 哦!好的,所以我可以制作一个类数组?我什至没有意识到这一点。谢谢!我会尝试一下,这应该会有所帮助!
  • std::string 是一个类似于 Dvd 的类
猜你喜欢
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多