2014-10-09 187 views
0

我需要在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文件內容就問我。我不認爲這個文件是需要的。

+0

你問如何實現'Crop :: Crop'? – 2014-10-09 23:36:42

+0

@RSahu沒有不真的。我必須將一個植物類的實例傳遞給crop類。像一個指針! – Sobasofly 2014-10-09 23:38:03

+0

@RSahu我認爲OP想要爲'Crop :: Crop(const Plant&,int,int)'實例化成員,並且不知道如何去做。至少我的水晶球說它是唯一缺少的代碼使它工作。 – luk32 2014-10-09 23:40:19

回答

5

有一種叫做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; 
} 

但尚未初始化明確地被用默認構造函數初始化任何成員,所以在//hereg_lenght存在,並且有一個值(0或垃圾,如果默認是我不記得零,我認爲它是thrash),然後在正文operator=被調用。在第一種情況下,通過複製構造函數創建對象。

通常這不是一個很大的區別,但是對於更復雜的類型它可能很重要。特別是如果構建一個空對象需要很長時間,那麼賦值也很複雜。這只是爲了更好地設置對象一次,而不是創建它並使用operator=進行重置。

由於某種原因,我個人喜歡2nd的樣子,但它被認爲是一種糟糕的做法,因爲從邏輯上講,這些成員是從一開始就使用某些值構建的。

+0

是同樣的東西g_length = 1;和g_length(l);? – Sobasofly 2014-10-09 23:41:32

+0

是的,在這種情況下,它是'int'的一個拷貝構造函數。這和寫'int i(5);'是一樣的。唯一的區別是,這些成員是在機構之前初始化的,這被認爲是一種好的做法。也許在技術上,它們會被設置兩次,因爲它們會使用默認的構造函數創建,然後通過body中的operator ='設置。 – luk32 2014-10-09 23:45:36

+0

+1爲清楚和解釋 – 2014-10-09 23:58:30

1

你在這裏在正確的軌道上:

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) { 
    // ... 
} 

使用成員初始化列表,您的數據成員初始化直到我們需要在之後執行某些操作我們已經初始化了我們的數據成員之後,才需要構造函數體。

0

您的裁剪構造函數收到植物(和兩個整數)並完全忽略它們。嘗試:

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