在对象的另一个类中创建实例
Creating instance in an another class of an object
我需要在类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;
}
但是,任何未显式初始化的成员都会使用默认构造函数进行初始化,因此在//here
,g_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) {}
- 在C++中为链表类创建实例
- 在 C++ 中在堆栈上创建实例时如何保持多态性?
- 如何使用Qt在D-Bus上创建/实例化配对代理
- 共创建实例消耗高 CPU
- 从与"this"相同的模板创建实例?
- 如何在不创建实例的情况下获取类的方法成员的类型?
- 创建实例化所有其他类和子系统的类的目的是什么
- 我怎么可能从尚未定义某些成员方法的类创建实例?(C++)
- godot的NetSocket如何创建实例?
- VULKAN创建实例vk_out_of_host_memory
- 如何推动在LUA脚本上使用的现有/创建/实例化类对象
- 为什么不能在不创建实例的情况下使用多态类
- 共同创建实例在 32 位上崩溃
- 创建实例时静态变量的地址
- 使用虚拟函数创建实例,为什么
- ADO 连接创建实例在 Windows Server 2003 上失败
- 使用函数中的复制构造函数创建实例的副本,该函数获取作为基对象传递的实例
- 如何从字符串中存储的类型创建实例
- ccomptr _appdomain 创建实例返回系统找不到指定的文件
- 创建实例化类数组 - 语法