Allen Maki wrote:
/*
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