-
December 30th, 2010, 10:00 AM
#1
Question about structs in class which wouldn't save value.
I have a question about this particular code.
The structs would not save the value entered by the user into its class' attributes.
If you do not understand what i am talking about, please compile the code below. Can someone kindly explain what is the problem and how to fix it? Thank you for your time.
Code:
#include <iostream>
#include <string>
using namespace std;
class Sam
{
struct sample{
int a;
string b;
};
public:
void set_a();
void set_b();
int ret_a();
string ret_b();
};
void Sam::set_a()
{
int a1;
cout<<"Insert int a";
cin>>a1;
sample().a=a1;
}
int Sam::ret_a()
{
return sample().a;
}
void Sam::set_b()
{
string b1;
cout<<"Insert string b";
cin>>b1;
sample().b=b1;
}
string Sam::ret_b()
{
return sample().b;
}
int main()
{
Sam c;
c.set_a();
c.set_b();
cout<<c.ret_a()<<endl<<c.ret_b(); //It should output the same value inputted by the user
// but it shows nonsense. why is it so?
return 0;
}
-
December 30th, 2010, 10:29 AM
#2
Re: Question about structs in class which wouldn't save value.
Originally Posted by hayloiuy
Can someone kindly explain what is the problem
What does this line do?
It creates a temporary variable of type "sample". Temporary variables are destroyed as soon as the statement is executed, therefore nothing has happened.
You create a member variable.
Code:
#include <iostream>
#include <string>
using namespace std;
class Sam
{
struct sample{
int a;
string b;
};
sample mySampleA, mySampleB;
public:
void set_a();
void set_b();
int ret_a();
string ret_b();
};
void Sam::set_a()
{
int a1;
cout<<"Insert int a";
cin>>a1;
mySampleA.a=a1;
}
int Sam::ret_a()
{
return mySampleA.a;
}
Regards,
Paul McKenzie
-
December 30th, 2010, 10:58 AM
#3
Re: Question about structs in class which wouldn't save value.
AARGGGHHHH this is just a very very simple mistake which i overlook. I spent 2 hours thinking what is the problem. Imagine that. If there are any thumbs up in this forum i will give you a hundred. Thank you very much and i am very very deeply sorry for wasting your time.
-
December 30th, 2010, 02:20 PM
#4
Re: Question about structs in class which wouldn't save value.
If there are any thumbs up
There is... just add :thumb:
-
January 3rd, 2011, 10:13 AM
#5
Re: Question about structs in class which wouldn't save value.
Since copying a std::string object might be expensive changing the ret_b() method to
Code:
const std::string& Sam::ret_b() const
{
return b;
}
might be useful, too.
- Guido
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|