class snake
{
public:
void setAge(int a) {_age=a;}
int getLength();
private:
int _age;
}
int snake::getLength()
{
int age;
std::cin>>age;
setAge(age);
return age*3;
}
int main()
{
snake mary,joe,betty;
int numSnakes=3,length;
for(int i=0;i<numSnakes;i++)
{
length=SNAKE.getLength()
std::cout<<"The length of snake "<<SNAKE<<" is "<<length<<std::endl;
}
return 0;
}
where the program would iterate SNAKE as mary, joe and betty.
Okay, I see the problem. There is no operator<< for snake objects and there is no accessor for the _age attribute. So make an accessor and use it instead of *i. You cannot send a snake object to operator<< without defining that operator for the type. Don't have time to do that right now but let me show you something else.
#include <vector>
int main()
{
snake mary, joe, betty;
std::vector<snake> pit;
pit.reserve(3); // reserve for 3 otherwise the push_back might create more memory than needed.
pit.push_back(mary);
pit.push_back(joe);
pit.push_back(betty);
// first initialize i and end at the beginning
// second, if you want to name the snake then create attribute, accessor for it and send that
// to stream. Or define operator<< for snake and send *i to operator<<.
for(std::vector<snake>::iterator i = pit.begin(), end = pit.end();; i != end; ++i)
{
std::cout << "The length of snake " << " is " << i->getLength() << std::endl;
}
return 0;
}
Perhaps someone else can show you the operator<< or you can google for that.