I'm having trouble storing data read in from the keyboard into a private member array.
When I try to simply add the data using:
std::cin >> array[counter];
I get a long error: pasted here to save space
I'm currently trying to find a way to store the input into a temporary variable and then sending it to the array, but I get the same error.
Header:
template<class Type>
class Department
{
private:
const static int MAX = 4;
typedef std::string sArray[MAX];
typedef Type tArray[MAX];
std::string deptName;
sArray names;
tArray salary;
public:
Department(const std::string & dept);
bool Add() const;
...
...
};
Implementation:
template<class Type>
Department<Type> :: Department(const std::string & name)
{...}
template<class Type>
bool Department<Type> :: Add() const
{
if (IsFull())
return 0;
else
{
Type tempName;
Type tempSal;
std::cout << "\nAdd called\n";
std::cout << "Enter employee ID:\t"; std::cin >> tempName;
std::cout << "Enter employee salary:\t"; std::cin>>tempSal;
//What is the best way to add the data stored in tempName, and tempSal to the arrays in the class
return 1;
}
}
So, the issue came down to that the Add
method was marked as const
. The error message
invalid operands to binary expression ('std::istream'
(aka 'basic_istream') and 'const std::string' (aka 'const basic_string'))
std::cout << "Enter employee ID:\t"; std::cin >> employee[counter];
really means that the compiler cannot find any operator>> for std::istream (which is cin) that accepts a const std::string
There are two ways to solve this, which both have their advantages and disadvantages.
const
from Add
. The class members are now allowed to be changed (and the employee[counter] will be a std::string instead as far as Add
is concerned).However, Add can change all of the class members.
or
mutable
keyword to employee: mutable sArray employee;
this will make sArray allowed to be changed even from const
. However, now all const functions can change employee
.