My main function is this:
int main(int argc, char* argv[])
{
int l1, n;
Ball** ball;
l1=atoi(argv[1]);
n=atoi (argv[2]);
for(int i=0; i<n; i++)
ball[i] = new Basket(l1);
delete[] ball;
}
I have four classes:
class Ball{
public:
Ball() {}
virtual ~Ball() {}
virtual void hit() {...}
};
class Basket{
int d;
public:
Basket(int i) { d=i; cout << "I create a basket-ball.." << endl; }
~Basket() { cout << "A ball destroyed..." << endl; }
};
class Tennis{ /* similar with Basket*/ };
class Ping_pong{};
I want to create an array of objects that I could control their info, and with this code I take this:
I create a basket-ball
Segmentation fault
I'm new in programming..Please help..
I want to create an array of objects that I could control their info, and with this code I take this:
I create a basket-ball |
Your Basket Ball would be a special kind of ball, so your declarations become:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
class Ball
{
public:
Ball() {}
virtual ~Ball() {}
virtual void hit() {...}
};
class Basket : public Ball
{
int d;
public:
Basket(int i) { d=i; cout << "I create a basket-ball.." << endl; }
~Basket() { cout << "A ball destroyed..." << endl; }
};
|
To complete your example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
int main(int argc, char* argv[])
{
if (argc < 3)
return -1;
int l1=atoi(argv[1]);
int n=atoi(argv[2]);
// create ball container
Ball** ball = new Ball*[n]
// create balls
for(int i=0; i<n; ++i)
ball[i] = new Basket(l1);
// hit balls
for(int i=0; i<n; ++i)
ball[i]->hit();
// delete balls
for(int i=0; i<n; ++i)
delete ball[i];
// delete ball container
delete [] ball;
}
|
Last edited on
1) Please use code tags when posting code, to make it readable:
http://www.cplusplus.com/articles/z13hAqkS/
2) You're trying to use
Basket as if it inherited from
Ball. However, in your definition of
Basket, it doesn't inherit from anything!
EDIT: Ninja'd by kbw.
Last edited on
MikeyBoy 1) I'm new in the forum....I will certainly apply what you said
2) My mistake...I forget to write it in the question.
kbw Thank you for your useful points..