[英]C++ class/object function usage query
我有一個定義函數的類需要作為參數傳遞。 我想設置這個類的新實例(帶參數)作為對象(?)。
陷入語法困境。
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定義params,它將在類函數2中使用並分配一個該類型的對象(?),以便intellisense將它拾取。
偽:
int main(){
classname(20, 20) object;
object.classfunction2(50, 50);
}
謝謝!
你的主要是有點不知所措。
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.
}
有幾點需要注意:您嘗試調用第一個構造函數的方式是錯誤的,您需要變量名后面的參數。 請參閱下面的評論以了解另一件需要注意的事項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.