Sob*_*fly 0 c++ pointers class object instance
我需要在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 << "===============";
}
Run Code Online (Sandbox Code Playgroud)
class crop是我想要植物类实例的地方
class Crop {
private:
int g_length;
int w_width;
Plant PlantType;
public:
Crop();
Crop(const Plant&, int, int);
};
Run Code Online (Sandbox Code Playgroud)
我想要类作物实例的类植物
class Plant {
private:
char plant[20];
char p_symbol;
public:
Plant();
Plant(const char* n, char s);
};
Run Code Online (Sandbox Code Playgroud)
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){
}
Run Code Online (Sandbox Code Playgroud)
抱歉,如果我遗失了什么.真的很困惑,如果你需要Plant.cpp文件内容只是问我.我认为不需要该文件.
有一个称为成员初始化列表的东西,它的位置在其参数列表之后的构造函数定义中,前面是分号,后跟构造函数的主体.因此,要初始化成员,您可以编写
Crop::Crop(const Plant& temp, int l, int w) :
g_length(l),
w_width(w),
PlantType(temp)
{ }
Run Code Online (Sandbox Code Playgroud)
这样做是为了调用成员的适当构造函数.它们不必是复制构造函数.您可以显式调用默认值或其他任何值,但在您的情况下可能没有多大意义.
这是因为在执行构造函数体之前实例化成员.你不会有ints的问题,因为它们可以设置在体内.但是,引用必须始终有效,因此正文中的任何内容都不会有"空引用".
你可以这样做:
Crop::Crop(const Plant& temp, int l, int w) : PlantType(temp)
{
g_length = l;
w_width = w;
}
Run Code Online (Sandbox Code Playgroud)
但是任何未显式初始化的成员都会使用默认构造函数进行初始化,因此在//here g_lenght存在且有一个值(0或者我不记得默认值是零,我认为它是捶打),然后在正文中operator=被调用.在第一种情况下,通过复制构造函数创建对象.
通常这不是一个很大的区别,但对于更复杂的类型,它可能很重要.特别是如果构造一个空对象需要很长时间,那么赋值也很复杂.它只是为了更好地设置对象一次,而不是创建它并重置operator=.
我个人喜欢第二种因为某种原因,但它被认为是一种更糟糕的做法,因为从逻辑上讲,这些成员的意思是从一开始就使用某些值构建.
| 归档时间: |
|
| 查看次数: |
4112 次 |
| 最近记录: |