Piotre Ugrumov wrote:
>
> Excuse me for the previous post, I have tried to modify the classes of the
> Savannah example and now I succeed to compile the classes but I have a
> strange problem.
>
> When I declar an object of the class Savan, I cannot see the methdo of the
> class:
> Savan s();
This does *not* define an object. It does something completely different:
It declares a function s, which takes no arguments and returns a Savan object.
You want:
Savan s;
> Leone l(........);
> s.addLeone(l);
> the methdo addLeone() isn't view, but all the method of the class Savan
> aren't view.
> //Savan s();
> //s.addLeone(l);
> error C2228: the element on the left ".addLeone" must have a type class,
> structure or union
> the type is "overloaded-function"
> Why this behaviour?
Because there is a C++ rule: if something could be a function declaration,
then it *is* a function declaration (a prototype).
Savan s();
looks like a function declaration in the same way as eg.
double MyFunction();
does. Thus the compiler treats it as such.
>
> Another question:
> How can I do to add an object to a dynamic array:
> I have defined 2 pointer and two int:
>
> Leone *lPtr;
> Zebra *zPtr;
> int lsize, zsize;
>
> For add an object to lPtr or zPtr, I have defined the method in this way:
> void Savan::addLeone(Leone &l){
> Leone *tmp;
> tmp=lPtr;
> lsize=lsize+1;
> lPtr=new Leone[lsize];
> lPtr=tmp;
> lPtr[lsize-1]=l;
> delete[] tmp;
> }
> Is correct what I write?
No.
void Savan::addLeone(Leone &l)
{
Leone* tmp;
tmp = lPtr;
lptr = new Leone[lsize + 1];
for( int i = 0; i < lsize; ++i ) {
lptr[i] = tmp[i];
}
lsize++;
lptr[lsize-1] = l;
delete [] tmp;
}
But even now, there are things that can go wrong (eg. what happens
if the memory allocation failes).
Given your current knowledge, it's best to not do the dynamic memory
management by yourself (there are lots of pitfalls), but instead let
a prebuilt class do it. C++ comes with such a class and it is called vector
#include <string>
#include <vector>
#include <iostream>
class Item
{
public:
Item( const std::string& Name ) : m_Name( Name ) {}
std::string Name() { return m_Name; }
private:
std::string m_Name;
};
class MyTest
{
public:
void Add( const Item& NewItem )
{
m_Items.push_back( NewItem );
}
void PrintAll()
{
for( int i = 0; i < m_Items.size(); ++i )
std::cout << m_Items[i].Name() << '\n';
}
private:
std::vector< Item > m_Items;
};
int main()
{
MyTest TheContainer;
Item Chest( "Chest" );
TheContainer.Add( Chest );
TheContainer.Add( Item( "Chair" ) );
TheContainer.Add( Item( "Lion" ) );
TheContainer.PrintAll();
return 0;
}
--
Karl Heinz Buchegger