Some help with class member functions and pointers
Hello. I've been working with Sams Teach Yourself C++ in 24 hours and Accelerated C++ over the past few weeks. I designed a simple Cat class that is almost identical to the one they use in the book. The problem comes in validating the data for the setage function. I've made an attempt at it and it works, but it seems a bit messy. I'd like to be able to simply call the setage function and have it do all of this without having to test for the return statements in the main function.
Also, I have a question about the pointers that I'm using. I plan to make other animal classes and some type of zoo program (to practice using classes). Will the method I'm using still work if I have an array of Cat objects? I don't really understand what the syntax to call the function would be in that case. I'd appreciate any answers and suggestions you can give, even if it isn't the answer to all of them.
Thanks,
Matt
main .C file. I'd like to integrate the catage function into the cat.h file, posted below, which contains the member functions so I don't have that loop in main.
Code:
#include<iostream>
#include<string>
#include "cat.h"
int catage(Cat *one);
int main()
{
std::cout << "What is the cat's name? ";
std::string name;
std::cin >> name;
Cat * buck = new Cat;
buck->setname(name);
int test=1;
while(test!=0)
{
test=catage(buck);
}
buck->meow();
std::cout << buck->getname() << " is " << buck->getage() << " year(s) old.\n";
buck->meow();
delete buck;
buck = 0;
return 0;
}
int catage(Cat *one)
{
std::cout << "How old is " << one->getname() << "? ";
int catage=0;
std::string badchars;
if(!(std::cin >> catage))
{
std::cin.clear();
std::cin >> badchars;
std::cout << "\"" << badchars << "\"" << " is not a number! Please try again\n";
return 1;
}
else if(catage < 0 || catage > 20)
{
std::cout << catage << " is a strange age for a cat! Try again.\n";
return 1;
}
else
{
one->setage(catage);
return 0;
}
}
the .h file. . .
Code:
#ifndef _cat_H_
#define _cat_H
#include<iostream>
#include<string>
class Cat
{
private:
int itsage;
std::string itsname;
public:
void setage(int age);
int getage();
void meow();
void setname(std::string name);
std::string getname();
Cat();
Cat(std::string name);
~Cat();
};
//default constructor
Cat::Cat()
{
itsname="";
}
//setage sets the cat's age
void Cat::setage(int age)
{
itsage = age;
}
//returns the cat's age
int Cat::getage()
{
return itsage;
}
//meow has the cat meow
void Cat::meow()
{
std::cout << "Meow\n";
}
//setname sets the cat's name
void Cat::setname(std::string name)
{
itsname = name;
}
//getname returns the cat's name
std::string Cat::getname()
{
return itsname;
}
//constructor
Cat::Cat(std::string name)
{
itsname = name;
}
//destructor
Cat::~Cat()
{
}
#endif
P.S. I'm not very good with pointers. It took me quite a while to even get this bit to work.