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:

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:

stream&
operator<<(std:

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
*/