我無法弄清楚我做錯了什麼?我有一個班級,其中有私人數據:C++訪問該類的私人數據
static const int SIZE = 101;
int *ptr;
int set [SIZE];
而我有2個構造函數。一個是將數組設置爲0的默認構造函數。 另一個需要5個參數並將數組中的5個值設置爲1. 我需要打印此數組。當我在構造函數中一切正常時,當我在構造函數內執行cout < <時,結果是正確的。但是當我嘗試使用功能打印。結果是垃圾。我做錯了什麼?
IntegerSet::IntegerSet() //default constructor
{
int set[SIZE] = {0};
ptr = set;
cout << "Default Constructor: " << endl;
for (int i =0; i<SIZE ;i++)
{
cout << set[i] << " ";
}
cout << endl;
}
IntegerSet::IntegerSet(int a, int b, int c, int d, int e)
{
int set[SIZE] = {0};
ptr = set;
ptr[a] = ptr[b] = ptr[c] = ptr[d] = ptr[e] = 1;
cout << "Constructor with 5 parametrs: " << endl;
for (int i =0; i<SIZE ;i++)
{
cout << ptr[i] << " ";
}
cout << endl;
}
void IntegerSet::print() const
{
bool flag = false;
cout << "I am in print: " << endl;
for (int i=0;i<SIZE;i++)
{
if (ptr[i]==1)
{
cout << i << " ";
flag = true;
}
}
if (flag == false)
cout << "-----";
cout << endl;
}
void main()
{
IntegerSet s1;
IntegerSet s2(1,50,10,22,98);
s2.print();
}
它的垃圾因爲set在堆棧中,所以指針(ptr)在退出構造函數時無效。 – drescherjm
我該怎麼辦? – user2001019
改爲使用矢量,不要在構造函數中重新聲明它。 – drescherjm