如何实例化多个 set 对象来测试 Set 类的各种构造函数和方法
How do I instantiate several set objects to test the various constructors and methods of my Set Class?
//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];
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 初始化具有非默认构造函数的std::数组项的更好方法
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 如果子类中没有构造函数方法,则错误"no matching function for call to 'LGame::LGame(String&)'"
- 复制构造函数方法的用法
- 为什么在类构造函数方法中,std::string 参数在调试时显示不同的结果?
- 我的构造函数方法不接受参数(DirectX / Windows)
- 带有常量构造函数参数的C++变量构造函数方法
- 在构造函数方法中返回一个子类
- 在模板专用化中添加单个构造函数方法
- 传递字符串指针然后检查构造函数/方法中的大小时出现问题
- 为什么基类的构造函数方法被调用两次?
- 不同的类模式:条件构造函数/方法与继承
- 我不能有一个将多个整数作为参数的构造函数方法/原型吗?阿杜伊诺
- Constexpr类与数组构造函数方法
- 通过显式调用构造函数(方法)来构造对象