[英]How can I make my program accept pointers?
I am trying to make my program accept pointers as part of a requirement to deallocate the heap space and kill the pointer.我试图让我的程序接受指针作为释放堆空间并终止指针的要求的一部分。 My program runs fine without the adjustments I attempted to make to accept pointers.我的程序运行良好,没有我试图接受指针的调整。 I'm getting the following error我收到以下错误
lab.cpp: In function 'int main()':
lab.cpp:21:19: error: request for member 'unit' in 'shipment', which is of pointer type 'cargo*'
(maybe you meant to use '->' ?)
21 | input(shipment.unit);
| ^~~~
lab.cpp:22:20: error: request for member 'unit' in 'shipment', which is of pointer type 'cargo*'
(maybe you meant to use '->' ?)
22 | output(shipment.unit);
| ^~~~
Here is my program without the adjustments, really simple but it works.这是我没有调整的程序,非常简单,但它有效。 All it's doing is taking input and outputting it, just setting it up for now as my assignment is to collect data from user and output it while deallocating the heapspace它所做的只是输入和输出它,现在只是设置它,因为我的任务是在释放堆空间的同时从用户和 output 收集数据
#include <iostream>
#include <string>
using namespace std;
struct cargo{
string unit;
string unitID;
int airCraft;
int weight;
string destination;
};
void input(cargo shipment){
cout << "Is it a pallet or a container?" << endl;
getline(cin, shipment.unit);
}
void output(cargo shipment){
cout << shipment.unit << endl;
}
int main() {
cargo shipment;
input(shipment);
output(shipment);
return 0;
}
Here is my program with my adjustments这是我的调整程序
#include <iostream>
#include <string>
using namespace std;
struct cargo{
string unit;
string unitID;
int airCraft;
int weight;
string destination;
};
void input(cargo *shipment){
cout << "Is it a pallet or a container?" << endl;
getline(cin, shipment.unit);
}
void output(cargo *shipment){
cout << shipment.unit << endl;
}
int main() {
cargo *shipment = new cargo;
input(shipment.unit);
output(shipment.unit);
delete shipment;
shipment = nullptr;
return 0;
}
When accessing an pointer's members, you need to use the arrow ( ->
) operator.访问指针的成员时,您需要使用箭头 ( ->
) 运算符。 But your methods input
and output
takes the cargo
pointer.但是您的方法input
和output
采用cargo
指针。 After accessing its member, you'll return the member, not the pointer.访问其成员后,您将返回成员,而不是指针。 So by doing shipment.unit
, your returning a string.因此,通过shipment.unit
,您将返回一个字符串。
To fix it, lest just pass in the pointer.要修复它,以免只传递指针。
void input(cargo *shipment){
cout << "Is it a pallet or a container?" << endl;
getline(cin, shipment->unit);
}
void output(cargo *shipment){
cout << shipment->unit << endl;
}
...
input(shipment);
output(shipment);
Additional: After deleting the shipment
, assigning it a nullptr
is useless.附加:删除后,给它nullptr
shipment
没有用的。 Your not gonna use it anyway.反正你不会用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.