如何解决如何使用构造函数C ++使用数组初始化指针
在struct creat数组中创建指针create -1,使用for循环初始化10次,并在struct中使用method进行打印-1,10次。
struct hasha {
int* arr;
int l;
hasha(int no) {
arr[no];
l = no;
for (int i = 0; i < l; i++) {
arr[i] = -1;
}
}
void print() {
for (int i = 0; i < l; i++) {
cout << arr[i] << " ";
}
}
};
int main() {
hasha a(10);
a.print();
}
解决方法
我认为这是出于学习目的,否则您应该为此使用std::vector<int>
。
struct hasha {
int* arr;
size_t l; // size_t is an unsigned int type better suited for sizes
hasha(size_t no) : // use the member initializer list (starting with ":")
arr(new int[no]),// create the array
l(no)
{
// initialize the array with -1,"l" times using a for loop
for (size_t i = 0; i < l; ++i) {
arr[i] = -1;
}
}
// You need to delete the implicitly declared copy ctor and copy assignment operator
// to forbid copying hasha objects to not free the `int*` multiple times later.
hasha(const hasha&) = delete;
hasha& operator=(const hasha&) = delete;
// You need a destructor to free the memory you allocated:
~hasha() {
delete[] arr;
}
void print() {
for (size_t i = 0; i < l; ++i) {
std::cout << arr[i] << " ";
}
}
};
,
以下构造函数使用数组初始化指针:
hasha ::hasha (int a[]) : arr (a) {}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。