HighTechTalks DotNet Forums  

I am new to OOP

VC++.net microsoft.public.dotnet.languages.vc


Discuss I am new to OOP in the VC++.net forum.



Reply
 
Thread Tools Search this Thread Display Modes
  #1  
Old   
Allen Maki
 
Posts: n/a

Default I am new to OOP - 04-16-2006 , 10:21 PM






/*

I am new to OOP. I have problem in including an array in a class.

I would like to know why the following codes can be built

but can not be compiled. Thanks.

*/

#include <iostream>

using namespace std;

class Array

{

public:

int *item;

int capacity;

};

int main()

{


Array *Jan;

Jan = new Array;

Jan->capacity = 5;



for (int i =0; i<5; i++)

Jan->item[i] = i;


for(i =0; i<5; i++)

cout << Jan->item[i] << endl;

return 0;

}



Reply With Quote
  #2  
Old   
Carl Daniel [VC++ MVP]
 
Posts: n/a

Default Re: I am new to OOP - 04-16-2006 , 11:18 PM






Allen Maki wrote:
Quote:
/*
I am new to OOP. I have problem in including an array in a class.
I would like to know why the following codes can be built
but can not be compiled. Thanks.
*/

#include <iostream
using namespace std;
class Array
{
public:
int *item;
int capacity;
};

int main()
{
Array *Jan;
Jan = new Array;
Jan->capacity = 5;

for (int i =0; i<5; i++)
Jan->item[i] = i;

for(i =0; i<5; i++)
cout << Jan->item[i] << endl;

return 0;
}
Style problems aside, there are (at least) three problems with this code:

1. In the second for loop, the variable i is undefined. If you're using an
old C++ compiler this may compile, but with a newer, more
standards-compliant compiler it won.t You need to declare a new loop
variable for the second loop - the 'i' from the fist loop is gone.

for (int i = 0...

2. You never allocated any memory for an array, so assuming you fix the
for-loop scoping problem, the code will likely crash at runtime.

3. You used std::endl without #include-ing <iomanip>.

Here's a revised version to point you in the right direction:

#include <iostream>
#include <iomanip>

using namespace std;

class Array
{
private:
int* m_item;
int m_capacity;

public:
Array(int cap)
: m_capacity(cap),
m_item(new int[cap])
{
}

int& operator[](int index)
{
return m_item[index];
}

int capacity() const
{
return m_capacity;
}
};

int main()
{
Array Jan(5);

for (int i =0; i<5; i++)
Jan[i] = i;

for(int i =0; i<5; i++)
cout << Jan[i] << endl;

return 0;
}

-cd





Reply With Quote
Reply




Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.