我正在开发一些能够接收字符串输入文件并根据用户输入文件组织它们的东西。输入文件的顶部是它的组织方式,其余的是格式化信息,每个信息都在它自己的行上,以便输入到对象中。我的对象所需的每条信息都分为5个连续的行。
我的问题是print函数,它将在对象指针数组上调用,并在调用时传入用户排序首选项。到目前为止我发现的是我甚至无法调用对象上的函数。我尝试了一些不同的解决方案,比如创建一个全新的对象(Object myObject();)并在其上调用相同的print函数,但这也无法解决。有没有办法在指向我创建的对象的数组上调用该函数并传入该首选变量?我已经尝试添加一个默认构造函数并在其上调用函数,但是当我这样做时,object.cpp中的两个测试在调用print时调用变量表明变量可能以NULL形式传递。
main.cpp中
#include <iostream>
#include <string>
#include "object.h"
int main()
{
Object **ptr = new Object*[5];//Create array of object pointers
string firstLine, secondLine, thirdLine, userPreference;
float fourthLine;
int fifthLine;
string currentLine;
int lineCounter = 0;
int arrayCounter = 0;
getline(cin, userPreference);//Preference on sorting method
while(getline(cin, currentLine)) {//Main loop
switch(lineCounter) {
case(1):
firstLine = currentLine;
lineCounter++;
break;
case(2):
secondLine = currentLine;
lineCounter++;
break;
case(3):
thirdLine = currentLine;
lineCounter++;
break;
case(4):
fourthLine = stof(currentLine);//Get float value of currentLine and set fourthLine equal to it
lineCounter++;
break;
case(5):
fifthLine = stoi(currentLine);//Get integer value of currentLine and set fithLine equal to it
ptr[arrayCounter] = new Object(firstLine, secondLine, thirdLine, fourthLine, fifthLine);
arrayCounter++;//Step to next element now that the current element is filled
lineCounter = 0;//Reset lineCounter
cout << "case 5 test" << endl;
break;
}//End switch
}
ptr -> print(userPreference);
for(int i = 0; i < arrayCounter; i++) {//Delete everything
cout << "Test";
}
}
object.cpp
#include "object.h"
#include <iostream>
using namespace std;
Object::Object(string title, string URL, string comment, float length, int rating) {
vidTitle = title;
vidURL = URL;
vidComment = comment;
vidLength = length;
vidRating = rating;
}
void Object::print(string preference) {
vidPreference = preference;
cout << vidPreference;
cout << preference;
if(vidPreference == "rating") {
//Rating sort
//Is the array passed through correctly? If so, can I climb through like I do to assign it in main?
}
if(vidPreference == "length") {
//Length sort
}
if(vidPreference == "title") {
//Title sort
}
else {
cout << preference << " is not a legal sorting method, giving up." << endl;
}
}
object.h
#ifndef OBJECT_H
#define OBJECT_H
#include <string>
using namespace std;
class Object
{
public:
Object(string title, string URL, string comment, float length, int rating);
void print(string preference);
private:
string vidTitle, vidURL, vidComment, vidPreference;
float vidLength;
int vidRating;
};
#endif
用于
ptr -> print(userPreference);
如果ptr
是Object*
类型将是有效的。由于它是Object**
类型,因此您需要使用一个计算结果为Object*
的表达式。例如,
for(int i = 0; i < arrayCounter; i++)
{
ptr[i]->print(userPreference);
}