有一个家庭作业,我应该在其中创建一个指向对象的指针向量
稍后,我将使用继承/多态性来扩展类,以包括两天交货、次日空运等费用。但是,这不是我现在关心的问题。当前程序的最终目标是打印出向量中每个对象的内容(名称和地址)并找到它的运输成本(重量*成本)。
我的麻烦不在于逻辑,我只是对与对象/指针/向量相关的几点感到困惑。但首先是我的代码。我基本上删掉了现在不重要的所有内容,int main,将有用户输入,但现在我硬编码了两个示例。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Package {
public:
Package(); //default constructor
Package(string d_name, string d_add, string d_zip, string d_city, string d_state, double c, double w);
double calculateCost(double, double);
~Package();
private:
string dest_name;
string dest_address;
string dest_zip;
string dest_city;
string dest_state;
double weight;
double cost;
};
Package::Package()
{
cout<<"Constucting Package Object with default values: "<<endl;
string dest_name="";
string dest_address="";
string dest_zip="";
string dest_city="";
string dest_state="";
double weight=0;
double cost=0;
}
Package::Package(string d_name, string d_add, string d_zip, string d_city, string d_state, string r_name, string r_add, string r_zip, string r_city, string r_state, double w, double c){
cout<<"Constucting Package Object with user defined values: "<<endl;
string dest_name=d_name;
string dest_address=d_add;
string dest_zip=d_zip;
string dest_city=d_city;
string dest_state=d_state;
double weight=w;
double cost=c;
}
Package::~Package()
{
cout<<"Deconstructing Package Object!"<<endl;
delete Package;
}
double Package::calculateCost(double x, double y){
return x+y;
}
int main(){
double cost=0;
vector<Package*> shipment;
cout<<"Enter Shipping Cost: "<<endl;
cin>>cost;
shipment.push_back(new Package("tom r","123 thunder road", "90210", "Red Bank", "NJ", cost, 10.5));
shipment.push_back(new Package ("Harry Potter","10 Madison Avenue", "55555", "New York", "NY", cost, 32.3));
return 0;
}
所以我的问题是:
我被告知我必须使用对象指针的向量,而不是对象。为什么?我的任务特别要求它,但我也被告知它不会起作用。
我应该在哪里创建这个向量?它应该是我的包类的一部分吗?那我该如何去添加对象呢?
我需要一个复制构造函数吗?为什么?
解构对象指针向量的正确方法是什么?
任何帮助,将不胜感激。我在这里搜索了很多相关文章,我意识到我的程序会有内存泄漏。我无法使用 boost:: 中的一个专用 ptrs。现在,我更关心的是如何构建我的程序的基础。这样我就可以真正深入了解我需要创建的功能。
谢谢。
原文由 Staypuft 发布,翻译遵循 CC BY-SA 4.0 许可协议
可以重用指针向量来存储子类的对象:
理想情况下,向量应该包含在一个类中。这使得内存管理更容易。它还有助于在不破坏现有客户端代码的情况下更改支持数据结构(此处为
std::vector
):所以我们可以将我们的代码重写为:
熟悉 三法则 将帮助您决定何时将复制构造函数添加到类中。另请阅读有关 const 正确性 的信息。