constructor

H

heng

I want to use iostream objects to initialize the data members:

class A
{
public:
int x;
A(iostream &t):x(t){}
};

int main()
{
A aobj(cin);
cout<<aobj.x;
}

Could you please tell me the correct coding? Thanks all.
 
J

Jim Langston

heng said:
I want to use iostream objects to initialize the data members:

class A
{
public:
int x;
A(iostream &t):x(t){}
};

int main()
{
A aobj(cin);
cout<<aobj.x;
}

Could you please tell me the correct coding? Thanks all.

Um, no. x is an int, yet you are trying to initialize it to an iostream
reference. I don't think initilziaion will work for you, this might
(untested)

class A
{
public:
int x;
A(iostream &t) { t >> x };
};

int main()
{
A aobj( std::cin );
std::cout << aobj.x;
}
 
S

Salt_Peter

heng said:
I want to use iostream objects to initialize the data members:

class A
{
public:
int x;
A(iostream &t):x(t){}
};

int main()
{
A aobj(cin);
cout<<aobj.x;
}

Could you please tell me the correct coding? Thanks all.

The name iostream refers to the i/o stream library implementation.
A reference to an input stream is gotten via a std::istream& reference.

You can use std::eek:stream& and std::istream& with some operator
overloads to get what you seek.
What you might not want to do is parse std::cin into your objects
directly since that wipes out any hope of detecting possible error
conditions (like sending an invalid integer).

#include <iostream>
#include <ostream>

class A
{
int x;
public:
A() : x(0) { }
A(int n) : x(n) { }
A& operator<<(const int n)
{
x = n;
return *this;
}
A& operator<<(const A& r_a)
{
x = r_a.x;
return *this;
}
friend std::istream&
operator>>(std::istream& is, A& r_a)
{
is >> r_a.x;
return is;
}
friend std::eek:stream&
operator<<(std::eek:stream& os, const A& r_a)
{
return os << r_a.x;
}
};

int main()
{
A instance;
A another(44);
std::cout << "another = ";
std::cout << another << std::endl;
int n(99);
std::cout << "instance = ";
std::cout << ( instance << n ) << std::endl;
std::cout << "another = ";
std::cout << ( another << instance ) << std::endl;

A a;
std::cout << "enter an integer: ";
std::cin >> a;
if( std::cin.good() )
{
std::cout << "a = ";
std::cout << a << std::endl;
}
}

/*
another = 44
instance = 99
another = 99
enter an integer: 2
a = 2
*/
 
H

Harry

heng said:
I want to use iostream objects to initialize the data members:

class A
{
public:
int x;
A(iostream &t):x(t){}
};

int main()
{
A aobj(cin);
cout<<aobj.x;
}

Could you please tell me the correct coding? Thanks all.

Pass the parameter to the constructor as:

A(istream & t){
t>>x;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top