Question:
c++ assignment problem?
Hovhannes
2012-04-12 23:45:45 UTC
Hi i got an assignment from my c++ class and I have a problem with it, I wont put actual assignment here (Its too long) but i simulated the same problem in small program. Basically what im trying to do is pass an argument from main to class, but its gona be storet in struct. and i have no idea what argument i should pass from main, i tried to pass string c string. dont know how to do it. please help :)


///Header file

#include
using namespace std;
const int MAX=5;



struct Passenger {
char name[80];
};



class Input
{
private:
Passenger passengers[MAX];

public:
void inputData(Passenger);

};


///main


#include "item1.h"
using namespace std;

int main()

{
Input e;
cout<<"Please enter name ";


e.inputData( /*What should i put here ?*/ );



return 0;

}
Three answers:
2012-04-13 00:33:28 UTC
Your question is exactly the right one: WHAT makes you think you can initialize a class object by passing it a class object UNLESS the pased object has been initialized somehow else??

Its a bootstrap problem. In other words it. is. wrong. It is a (common) error in the program logic.

You can input an array of char, or (IMO) better, a string as long as you have a constructor to initialize the instantiation.

string str1;

cin >> str1;

Passenger P1(str1);

Input io(P1);

But unless I am missing something what you've written has an additional problem: input is something you do TO the data member or a Passenger. Yet you have created a class Input that has a Passenger member????? Totally bass-ackwards, if you ask me

A public method (member function) (possibly as suggested a constructor) is someting that should populate the (private) data members (fields). Seems to me.

So

class Passenger

{

public:

…addName(char* s);



private:

…char[MAX_STRING] Name;



};

with the right logic you won't chase your tail.

Personally, I'd use a constructor rather than the addName function.
James Bond
2012-04-12 23:56:31 UTC
struct Passenger {

char name[80];

};







class Input

{

private:

Passenger passengers[MAX];



public:

void inputData(Passenger);



};





///main





#include "item1.h"

using namespace std;



int main()



{

Input e;

char x[20];

for(int i=0;i<5;i++){

cout<<"Please enter name ";

struct Passenger P;



cin>>x;





strcpy(P.name.x);

e.inputData(P );

}





return 0;



}
deparvine
2016-12-02 14:52:33 UTC
you could desire to declare the class yet with distinctive information types. that's how the compiler is usual with what function to apply. That way once you declare the class of a particular kind, it only makes use of the class matching the counsel kind. subsequently, overloaded.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...