各位大神好,我在用類別實作Array時出了一點小狀況
很不幸的在做出陣列的時候,陣列的size完全跟輸入的size 不一樣
以下我的程式碼
#include <iostream>
#include <cstdlib>
class CppArray
{
public:
CppArray(int, float); // Constructor
CppArray(const CppArray &); // Copy constructor
CppArray &operator=(const CppArray &); // Assigner
~CppArray(); // Destructor
float &operator[](int); // Subscript operator
int getSize(void) const; // Sizeof array
float *getHead() const; // Get the pointer of head of the array
friend std::istream &operator>>(std::istream &, CppArray &); // Overload operator >>
friend std::ostream &operator<<(std::ostream &, CppArray &); // Overload operator <<
private:
int size;
float initvalue;
float *head = nullptr;
};
CppArray::CppArray(int size = 1, float initValue = 0.0)
{
std::cout << "Constructor" << std::endl;
this->head = new float[size];
for (int i = 0; i < size; ++i)
{
*(head + i) = initValue;
}
}
CppArray::CppArray(const CppArray &cppArr)
{
std::cout << "Copy constructor" << std::endl;
this->size = cppArr.size;
this->head = new float[this->size];
for (int i = 0; i < this->size; ++i)
{
*(this->head + i) = *(cppArr.head + i);
}
}
CppArray &CppArray::operator=(const CppArray &cppArr)
{
std::cout << "operator=" << std::endl;
delete[](this->head);
this->size = cppArr.getSize();
this->head = new float[this->size];
for (int i = 0; i < this->size; ++i)
{
*(this->head + i) = *(cppArr.getHead() + i);
}
return *this;
}
CppArray::~CppArray()
{
std::cout << "destructor" << std::endl;
delete[] head;
}
float &CppArray::operator[](int x)
{
std::cout << "operator[]" << std::endl;
if (x >= this->size)
{
std::cout << "Index out of range...";
return (this->head)[0];
}
else
{
return (this->head)[x];
}
}
int CppArray::getSize() const
{
std::cout << "getSize()" << std::endl;
return this->size;
}
float *CppArray::getHead() const
{
std::cout << "getHead()" << std::endl;
return this->head;
}
std::istream &operator>>(std::istream &is, CppArray &cppArr)
{
std::cout << "operator>>" << std::endl;
for (int i = 0; i < cppArr.size; i++)
{
is >> cppArr.head[i];
}
return is;
}
std::ostream &operator<<(std::ostream &os, CppArray &cppArr)
{
std::cout << "operator<<" << std::endl;
for (int i = 0; i < cppArr.size; i++)
{
os << cppArr.head[i] << std::endl;
}
return os;
}
int main(void)
{
CppArray arr(5, 100);
std::cout << arr.getSize();
system("pause");
return 0;
}
印出的size與初始化的值不同
謝謝大家的幫忙
話說, 沒有人迴圈在用 ++i 的吧,
看起來你好像變成從1開始...