簡體   English   中英

在 C++ 中調用函數

[英]calling functions in C++

我試圖在 C++ 中調用一個函數,我認為它與 C 中的函數相同,但是在嘗試將 C 程序轉換為 C++ 時,我遇到了一個錯誤,它說函數未聲明。

這是我的課:

class contacts
 {
  private:;
          char *First_Name;
          char *Last_Name;
          char *home;
          char *cell;
  public:;
  //constructor
         contacts()
         {
         }  
//Function declaration     
void readfile (contacts*friends ,int* counter, int i,char buffer[],FILE*read,char user_entry3[]);

  };

這是我的菜單功能的一個片段:

 if(user_entry1==1)
  {
    printf("Please enter a file name");
    scanf("%s",user_entry3); 
    read=fopen(user_entry3,"r+");

   //This is the "undeclared" function
   readfile(friends ,counter,i,buffer,read,user_entry3);
   }else;

我顯然做錯了什么,但是每次我嘗試編譯時,我都會得到readfile undeclared(first use this function)我在這里做錯了什么?

您需要創建一個contacts類的對象,然后在該對象上調用readfile 像這樣: contacts c; c.readfile(); contacts c; c.readfile(); .

班級內部的“菜單”功能是否有contacts 按照您的設計方式,它只能在類的實例上調用。 您可以根據readfilecontacts確切含義進行選擇

我猜該函數讀取所有聯系人而不僅僅是 1 個聯系人,這意味着它可以成為靜態函數

static void readfile(... ;

並稱為

contacts::readfile(...;

或者,如果您不需要直接訪問類的內部結構,您可以在類外聲明它(作為自由函數,類似於普通 C 函數)並完全按照您現在的方式使用。 這實際上是編譯器在遇到您的代碼時正在搜索的內容。

另外,我建議您重命名class contacts -> class contact因為每個對象似乎只包含 1 個人的聯系信息。

我建議重構以使用 STL 向量。

#include <vector>
#include <ReaderUtil>

using namespace std;

vector< contact > myContactCollection;
myContactCollection.push_back( Contact("Bob",....) );
myContactCollection.push_back( Contact("Jack",....) );
myContactCollection.push_back( Contact("Jill",....) );

或者...

myContactCollection = ReaderClass::csvparser(myFile);

在哪里

ReaderClass::csvparser(std::string myFile) returns vector<Contact>

由於您的 readfile 函數位於contacts 類中,因此上面的答案在技術上是正確的,因為您需要創建對象的實例然后調用該函數。 但是,從 OO 的角度來看,您的類函數通常應該只對包含它的類的對象的成員進行操作。 您在這里擁有的更像是一個通用函數,它接受多種類型的參數,其中只有一個是指向本身包含您正在調用的函數的類的指針,如果您考慮一下,這有點奇怪。 因此,您會將指向該類的指針傳遞給該類的成員函數,這將需要它的兩個實例。 您不能將類視為指向結構的指針的簡單替代。 由於這是一個類,因此您將所有需要的變量聲明為類的成員,因此無需將它們作為參數傳遞(類的要點之一是將一般數據與類成員數據隔離)。 這是一個更新,應該為您指明正確的方向。

   class contacts
     {
      private:

          char *First_Name;
          char *Last_Name;
          char *home;
          char *cell;
          FILE *read;  // these all could also be declared as a stack variable in 'readfile'


    public:
    //constructor

    contacts()
        {
        }  

    //destruction
    ~contacts()
    {
    }

    //Function declaration     
    int contacts::readfile (char * userEnteredFilename);

    };


    contacts myContact = new contacts();

    printf("Please enter a file name");
    scanf("%s",user_entry3); 

    int iCount = myContact->readfile(user_entry3);

    // the readfile function should contain all of the file i/O code 

暫無
暫無

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

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