//Header File
#ifndef SET_H
#define SET_H
class Set
{
private:
int * set;
int pSize;
int numElements;
static const int DEFAULT_SIZE=5;
public:
Set(int);
Set(int [], int);
Set(const Set&);
~Set();
void setSet();
void display();
};
#endif
// Member Implementation File
#include <iostream>
#include "Set.h"
using namespace std;
Set::Set(int SIZE = DEFAULT_SIZE) // Default Constructor
{
pSize = SIZE;
set = new int[pSize];
}
Set::Set(int arr[], int pSize) // Set Constructor
{
this->pSize = pSize;
set = new int [this->pSize];
for(int i =0; i < pSize; i++)
{
set[i] = arr[i];
}
}
Set::Set(const Set &obj) // Copy Constructor
{
pSize = obj.pSize;
set = new int[obj.pSize];
for(int i =0; i < pSize; i++)
{
set[i] = obj.set[i];
}
}
Set::~Set()
{
if(set != NULL)
delete []set;
set = NULL;
}
void Set::setSet()
{
cout << "Please enter a set of integers" << endl;
cin>> numElements;
while(numElements> pSize)
{
int *arr = new int[pSize + DEFAULT_SIZE];
for(int i = 0 ; i < pSize; i++)
{
arr[i] = set[i];
}
delete []set;
set = arr;
pSize = pSize + DEFAULT_SIZE;
}
for(int i =0; i < numElements; i++)
{
cout << "Please enter a number" << endl;
cin >> set[i];
}
}
void Set::display()
{
cout << "{";
for(int i =0 ; i < numElements; i++)
{
if (i == numElements - 1)
cout << set[i];
else
cout << set[i]<< ", ";
}
cout << "}" << endl;
}
//Main.cpp file
#include <iostream>
#include "set.h"
#include <cstdlib>
using namespace std;
int main()
{
Set myInstance[];
myInstance.display();
return 0;
}
如何将数组的不同实例从成员实现文件创建到主文件中?如何使用类、对象和调用数组专门格式化代码行?我是否需要在带有我的语句的文件中使用另一个 for 循环?请让我知道。
此外,我还需要一种方法将新元素添加到现有集合并相应地返回 {true, false}。根据定义,集合的元素不能因此,重复此方法必须首先确保元素添加 还不是集合的元素。如果元素不能另外,该方法应返回 false 来表示这一点。此方法应该能够向集合添加新元素,即使调用该方法时物理数组的容量(即元素数等于物理大小(。
问题 1
Set::Set(int)
的声明及其实施是不对的。
不能在定义中使用默认参数值。它们需要在宣言中。
class Set
{
...
Set(int SIZE = DEFAULT_SIZE); // Default Constructor
和
Set::Set(int SIZE)
{
pSize = SIZE;
set = new int[pSize];
}
问题2
Set myInstance[];
语法不正确。如果要创建单个实例,请使用:
Set myInstance;
如果要创建包含 10 个实例的数组,请使用:
Set myInstanceArray[10];