2012-03-30 31 views
0

我有一個類需要作爲參數傳遞定義的函數。 我想設置這個類的新實例(帶參數)作爲對象(?)。C++類/對象功能用法查詢

卡住的語法。

class classname{ 
void classfunction1(int, int); 
void classfunction2(int, int); 
}; 

void classname::classfunction1 (int a, int b) 
{ // function } 

void classname::classfunction2 (int a, int b) 
{ // function uses classfunction1 } 

我要定義classfunction1的參數,可以將在classfunction 2中可使用和分配對象(?),則該類型的,使得智能感知將它撿起來。

僞:

int main(){ 
classname(20, 20) object; 
object.classfunction2(50, 50); 
} 

謝謝!

+0

我很難理解你想要達到的目標,你的僞代碼沒有任何意義,對不起。你在尋找如何編寫構造函數嗎? – Mat 2012-03-30 12:23:01

回答

2

你的主要是在一分鐘有點won。。

int main(){ 
    classname(20, 20) object; // You are incorrectly calling a constructor which does not exist 
    object.classfunction2(50, 50); // more like correct behavior. 
} 

您已經定義沒有任何成員變量的類,所以也沒有store任何數據。它只有兩個功能。所以這意味着你可以使用編譯器爲每個類定義的「默認構造函數」(如果你願意,你可以提供你自己的)。

int main(){ 
    classname object; // Call the default constructor 
    object.classfunction1(10, 20); // Call the functions you want. 
    object.classfunction2(50, 50); 
} 

如果您想提供一個構造函數,你應該這樣做:

class classname{ 
    public: 
    classname(int variable1, int variable2): 
      member1(variable1), member2(variable2){}; //note that there is no return type 
    void classfunction1(); //because instead of taking parameters it uses member1 & 2 
    void classfunction2(int, int); 

    private: 
    int member1; 
    int member2; 
}; 

,您主要會再看看這樣的:

int main(){ 
    classname object(10, 20); // Call the default constructor. Note that the (10, 20) is AFTER "object". 
    object.classfunction1(); // Call the function... it will use 10 and 20. 
    object.classfunction2(50, 50); //This function will use 50, 50 and then call classfunction1 which will use 10 and 20. 
} 

幾件事情要注意:該方法你試圖調用第一個構造函數是錯誤的,你需要變量名後面的參數。 請參閱下面的註釋以瞭解另一件需要注意的事項。

+1

'classname(20,20)object;'不調用構造函數,實際上它沒有任何語言(這是非法的)。 'classname object();'也不調用構造函數,它是一個名爲'object'的函數的聲明,它沒有參數並且返回一個'classname'類型的對象。 – 2012-03-30 12:46:53

+0

@LucTouraille - 是關於錯誤位置的參數列表。我稍後指出了更正。 – Dennis 2012-03-30 12:50:56

+0

@LucTouraille關於另一件事......偶然的函數指針聲明,你是絕對正確的。我以前從未注意到這一點。將修改我的答案。 沒想到我會從這個問題中學到任何新的東西......但是,你去! – Dennis 2012-03-30 12:59:21