2016-05-15 21 views
1

我已經單獨實現並定義了方法。現在我不明白如何在Main.cpp文件中創建Parcel2類的對象/實例。我也寫在Main.cpp中Parcel2 :: Parcel2(2);但它的日誌說構造函數不能直接調用。請親引導我。如何在主函數中設置Parcel2類的對象

Parcel2.h

#ifndef PARCEL2_H 
#define PARCEL2_H 

class Parcel2 
{ 
    private: 
     // Declare data members 
     int id; 

    public: 
     // Constructor 
     Parcel2(int id); 

     // Setter function 
     void setID(int id); 

     // getter function 
     int getID(); 

    protected: 
}; 

#endif 

Parcel2.cpp

#include "Parcel2.h" 

// Defination of constructor 
Parcel2::Parcel2(int id) { 
    this->id = id; 
}  
// Defination of setter 
void Parcel2::setID(int id) { 
    this->id = id; 
} 

// Defination of getter 
int Parcel2::getID() { 
    return id; 
} 

Main7.cpp

#include <iostream> 
#include "Parcel2.h" 

/* run this program using the console pauser or add your own getch, system("pause") or input loop */ 

int main(int argc, char** argv) { 
    // how to make object 
} 

回答

2

如果你試圖在棧上創建一個對象Parsel2(作爲本地變量),你可以用一個整數參數聲明一個變量。 (需要整數參數,因爲你的構造需要一個參數。)例如:

Parcel2 obj(2); 

這裏是一個替代C++ 11語法,其中一些(我)找到容易解析:

auto obj = Parcel2(2); 

如果相反,你要動態分配一個Parsel2,你需要用new它分配:

Parcel2 * obj = new Parcel2(2); 

並再次,替代語法:

auto obj = new Parcel2(2); 

最後一點,請考慮將使用成員初始化列表類成員:

Parcel2::Parcel2(int id) : id(id) 
{} 
+0

感謝。我找到解決方案 –

相關問題