I am a newbie. I just want to write a class that accept input from cin command.
i don't know what to put (constructor or operator>> method???) in my Class A but I always run into compilation errors. Please enlighten me. Thank you
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
class A
{
};
int main()
{
A a;
cout << "enter something: ";
cin >> a;
}
Compile error:
g++ -Wall -c "test.cpp" (in directory: C:\Users\Terminal\Desktop\New folder)
test.cpp: In function 'int main()':
test.cpp:14:9: error: no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream<char>}' and 'A')
cin >> a;
^
In file included from c:\mingw\lib\gcc\mingw32\5.3.0\include\c++\iostream:40:0,
#include <iostream>
usingnamespace std;
class A {
int data;
public:
friend istream& operator>>(istream&, A&);
};
istream& operator>>(istream& in, A& a)
{
in >> a.data;
return in;
}
int main()
{
cout << "enter a number: ";
A a;
cin >> a;
}