在对象的另一个类中创建实例

Creating instance in an another class of an object

本文关键字:创建 实例 另一个 对象      更新时间:2023-10-16

我需要在类Crop of Plant类中创建一个实例,但我无法找到使其工作的方法。希望你们能帮忙。

这是我向类裁剪发送对象的主要位置。

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文件内容,只需问我。我认为不需要那个文件。

有一个称为成员初始值设定项列表的东西,它在构造函数定义中的位置在其参数列表之后,前面是分号,后面是构造函数的主体。因此,要初始化成员,您可以编写

Crop::Crop(const Plant& temp, int l, int w) : 
  g_length(l), 
  w_width(w), 
  PlantType(temp) 
{ }

这样做的目的是调用成员的适当构造函数。它们不必是复制构造函数。您可以显式地调用default one或任何其他方法,尽管在您的情况下这可能没有多大意义。

这是因为成员是在执行构造函数主体之前实例化的。int不会有问题,因为它们可以设置在主体内部。然而,引用需要始终有效,因此正文中的任何内容都不会有"null引用"。

你可以做:

Crop::Crop(const Plant& temp, int l, int w) : PlantType(temp) 
{ 
   g_length = l;
   w_width = w;
}

但是,任何未显式初始化的成员都会使用默认构造函数进行初始化,因此在//hereg_lenght存在并具有一个值(0或trash,如果默认值为零,我不记得了,我认为它是thrash),然后在主体中调用operator=。在第一种情况下,对象是通过复制构造函数创建的。

通常情况下,这并不是很大的区别,但对于更复杂的类型,这可能很重要。特别是如果构造一个空对象需要很长时间,那么赋值也很复杂。这只是为了更好地设置一次对象,而不是创建它并用operator=重置。

出于某种原因,我个人喜欢2nd的外观,但这被认为是一种更糟糕的做法,因为从逻辑上讲,这些成员从一开始就应该使用一些值来构建。

您在这里走上了正确的道路:

crop[0] = Crop(plant[0],4,2);

这将使用正确的参数调用类Crop的构造函数。这个构造函数应该用这些值初始化相应的数据成员,但实际接受这些参数的构造函数什么也不做:

Crop::Crop(const Plant& temp, int l, int w) {
    // ...
}

使用成员初始化器列表初始化数据成员:

Crop::Crop(const Plant& temp, int l, int w)
    : g_length(l), g_width(w), PlantType(temp)
{ }

在初始化数据成员之后需要执行操作之前,不需要构造函数主体。

Crop构造函数接收Plant(和两个整数)并完全忽略它们。尝试:

Crop::Crop(const Plant& temp, int l, int w) :
    g_length(l), w_width(w), PlantType(temp) {}