Here is part of my class assign_obj
, constructor and operator that I want to print the object.
When trying to compile operator I am getting error :
error: 'A' was not declared in this scope for(assign_obj::item anItem : obj.*A){
Why is that?
If I try obj.A
instead, I get error for the forloop as C can not loop a pointer of dynamic array.
class assign_obj{
private:
struct item{
char value;
int count;
};
item * A; //pointer A pointing to something of type Item
int size;
public:
assign_obj();
assign_obj(std::string);
friend std::ostream& operator<<(std::ostream & out, assign_obj & obj);
//Constructor
assign_obj::assign_obj(string aString){
size = aString.size();
A = new item[size];
item myItem;
for(int i = 0; i < size; i ){
myItem = {(char)toupper(aString[i]), 1};
A[i] = myItem;
}
}
// Print operator
std::ostream& operator<<(std::ostream & out, assign_obj & obj){
out <<"[ ";
for(assign_obj::item anItem : obj.*A){
out << anItem.value;
out << ":";
out << anItem.count;
out << " ";
}
out <<"]";
return out;
}
CodePudding user response:
You can't use a for loop that way for a dynamically allocated array. You can use a plain old for loop for your plain old array.
std::ostream& operator<<(std::ostream & out, assign_obj & obj){
out <<"[ ";
for (size_t i = 0; i < obj.size; i ) {
out << obj.A[i].value << ":"
<< obj.A[i].count << " ";
}
out <<"]";
return out;
}
CodePudding user response:
In c it is usually recomended to use std::vector
, instead of raw c arrays.
You need to add:
#include <vector>
Then your member will be:
std::vector<item> A;
Allocating the items in assign_obj::assign_obj
is done like this:
A.resize(size);
Finally your operator<<
will be:
std::ostream& operator<<(std::ostream & out, assign_obj & obj){
out <<"[ ";
//-----------------------vvvvvvv----------vvvvv--
for(assign_obj::item const & anItem : obj.A){
out << anItem.value;
out << ":";
out << anItem.count;
out << " ";
}
out <<"]";
return out;
}
Notes:
- Accessing the
A
member ofobj
is done withobj.A
, notobj.*A
. - Travresing the vector is done with a
const&
to avoid copy.