Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / Managed C++ / April 2006

Tip: Looking for answers? Try searching our database.

I am new to OOP

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Allen Maki - 17 Apr 2006 04:21 GMT
/*

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;

}
Carl Daniel [VC++ MVP] - 17 Apr 2006 05:18 GMT
> /*
> I am new to OOP. I have problem in including an array in a class.
[quoted text clipped - 25 lines]
> 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

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.