簡體   English   中英

在主類中調用類的函數

[英]Calling a function of a class in the main

我知道我們可以通過對象的主調用類的函數

 object.Function1(object);

但是有沒有辦法像下面這樣調用函數

  Function1(object);

我必須編寫一個類,該類將使用以下主要功能運行代碼

  int main() {
  Line line1(10);
  Line line2 = line1; 
  display(line1);
  display(line2);
  return 0;
   }

我不知道為什么需要它,但是您可以創建調用方法display的免費函數“ display”:

void display(Line& line)
{
    line.display();
}
int main() {
    Line line1(10);
    Line line2 = line1; 
    display(line1);
    display(line2);
    return 0;
}

為了補充Sandro的簡單但有效的建議,這里有一個更通用的建議,有人在評論中提到。

您可以使用mem_fn()創建一個與成員函數相對應的函數對象mem_fun_ref()如果在C ++ 11之前使用較早的C ++編譯器,則可以使用mem_fun_ref() )。

優點是您不必擔心返回類型和參數:

class C {
    public:
    void x() { cout << "Yes x!"<<endl; }
    void y(int a) { cout << "Yes y"<<a<<"!"<<endl; }
};

int main() {
    C c; 
    c.x(); 
    c.y(3); 

    auto x = mem_fn(&C::x);    // function object
    auto y = mem_fn(&C::y);
    x(c);                      // call them like a function 
    y(c,4);

    return 0;
}

在線演示

不便之處在於,這種輕松是有代價的:與Sandro的方法不同,對於不同的類,您不能對同一函數名進行不同的重載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM