在一个对象的另一个类中创建实例
我需要在Plant类的Crop类中创建一个实例,并且无法找到一种方法来实现这个工作。希望你们能帮上忙。在一个对象的另一个类中创建实例
这是我的主要发送对象的类作物。
int main(){
char select = 'a';
int plant_num = 2;
int crop_num = 0;
Crop crop[10];
Plant plant[20];
plant[0] = Plant("Carrots",'c');
plant[1] = Plant("Lettuce",'l');
plant[2] = Plant("Rosemary",'r');
crop[0] = Crop(plant[0],4,2);
crop_num++;
cout << "Garden Designer" << endl;
cout << "===============";
}
类作物就是我想要的我想在类作物的实例植物类
class Crop {
private:
int g_length;
int w_width;
Plant PlantType;
public:
Crop();
Crop(const Plant&, int, int);
};
类植物的实例
class Plant {
private:
char plant[20];
char p_symbol;
public:
Plant();
Plant(const char* n, char s);
};
Crop.cpp
#include <iostream>
#include <iomanip>
#include <cstring>
#include <new>
#include "crop.h"
using namespace std;
Crop::Crop(){
}
Crop::Crop(const Plant& temp, int l, int w){
}
对不起,如果我缺少一些事情。真的很困惑,如果你需要Plant.cpp文件内容就问我。我不认为这个文件是需要的。
有一种叫做Member initializer list的地方,它的位置在它的参数列表之后的构造函数定义中,前面是一个分号,后面跟着一个构造函数体。因此,初始化您可以编写的成员
Crop::Crop(const Plant& temp, int l, int w) :
g_length(l),
w_width(w),
PlantType(temp)
{ }
这样做是调用成员的相应构造函数。他们不必是复制构造函数。你可以明确地调用默认的或其他的,尽管在你的情况下它可能没有多大意义。
这是因为成员在执行构造函数的主体之前被实例化。你不会有int
s的问题,因为它们可以设置在体内。然而,参考文献需要在任何时候都有效,因此体内没有任何内容会有“空参考”。
你可以这样做:
Crop::Crop(const Plant& temp, int l, int w) : PlantType(temp)
{
g_length = l;
w_width = w;
}
但尚未初始化明确地被用默认构造函数初始化任何成员,所以在//here
g_lenght
存在,并且有一个值(0或垃圾,如果默认是我不记得零,我认为它是thrash),然后在正文operator=
被调用。在第一种情况下,通过复制构造函数创建对象。
通常这不是一个很大的区别,但是对于更复杂的类型它可能很重要。特别是如果构建一个空对象需要很长时间,那么赋值也很复杂。这只是为了更好地设置对象一次,而不是创建它并使用operator=
进行重置。
由于某种原因,我个人喜欢2nd的样子,但它被认为是一种糟糕的做法,因为从逻辑上讲,这些成员是从一开始就使用某些值构建的。
你在这里在正确的轨道上:
crop[0] = Crop(plant[0],4,2);
这将调用类Crop
与正确的参数构造函数。此构造函数应该初始化这些值对应的数据成员,但其实需要这些参数的构造函数什么也不做:
Crop::Crop(const Plant& temp, int l, int w)
: g_length(l), g_width(w), PlantType(temp)
{ }
:
Crop::Crop(const Plant& temp, int l, int w) {
// ...
}
使用成员初始化列表,您的数据成员初始化直到我们需要在之后执行某些操作我们已经初始化了我们的数据成员之后,才需要构造函数体。
您的裁剪构造函数收到植物(和两个整数)并完全忽略它们。尝试:
Crop::Crop(const Plant& temp, int l, int w) :
g_length(l), w_width(w), PlantType(temp) {}
你问如何实现'Crop :: Crop'? – 2014-10-09 23:36:42
@RSahu没有不真的。我必须将一个植物类的实例传递给crop类。像一个指针! – Sobasofly 2014-10-09 23:38:03
@RSahu我认为OP想要为'Crop :: Crop(const Plant&,int,int)'实例化成员,并且不知道如何去做。至少我的水晶球说它是唯一缺少的代码使它工作。 – luk32 2014-10-09 23:40:19