簡體   English   中英

在C ++中定義一個類

[英]Defining a class in c++

當我嘗試運行該程序時,出現錯誤消息:

“嚴重錯誤:sales_item.h:沒有這樣的文件或目錄。

#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item book;
std::cin >> book;
std::cout << book << std::endl;
return 0;
}

那是什么意思? 我讀過的這本書,《 C ++入門》第5版,教我用這種方式定義一個類。 這是錯的嗎? 為什么我不能運行該程序?

這意味着編譯器找不到您已要求將其包含在要編譯的文件中的名為Sales_item.h的文件。

猜測,這本書希望您創建一個具有該名稱的文件,並將其保存到上面存儲了源文件的相同子目錄中。

是的,這是錯誤的。

假設此代碼位於名為MyFile.cpp的文件中,那么您的代碼段假定該類的聲明位於與MyFile.cpp源文件相同的文件夾中的"Sales_item.h"文件中。

#include實際上是一個復制/粘貼指令,該指令將指定文件的內容復制到當前文件中,然后編譯器對其進行編譯。 現在, Sales_item.h文件不存在,並且編譯器向您顯示一個錯誤,找不到它。

聲明和定義類的正確方法:

#include <iostream>


// #include "Sales_item.h"
// What should be in the "Sales_item.h" file

#include <string>
class Sales_item
{

public:
    Sales_item(std::string itemName) //constructor
    {
        m_Name = itemName;
    };

    const char * GetName()
    {
       return m_Name.c_str();
    }

private: //member variables

    std::string m_Name;
};


// End "Sales_item.h"


int main()
{

    std::string bookName;
    std::cin >> bookName; //requires the user to type a string on the command prompt

    Sales_item book(bookName); //construct the object
    std::cout << book.GetName() << std::endl; // retrieve & print the item name on the command prompt
    return 0;
}

另一點是,在C ++中,您的類通常在頭文件(.h / .hpp)中聲明,並在(.cpp)文件中定義。 在我的示例中,僅在同一文件中聲明和定義了該類。 那是與您的問題要求不同的主題,但是如果您想了解有關如何使用C ++的良好編碼實踐進行編碼的更多信息,請閱讀有關C ++中的“聲明與定義”的更多信息。

最好的方法(但更復雜)是像這樣編寫我的示例: https : //gist.github.com/jeanmikaell/5636990

對於任何書籍,我建議您在編程之前先閱讀本簡要教程: http : //www.cplusplus.com/doc/tutorial/

看到這個鏈接

此鏈接的幾行內容:

如何宣布課程

可以在最終使用它們的文件中聲明類。 但是,最好在單獨的文件中定義它們。 然后可以在任何新應用程序中輕松重用這些類。 但是,創建和使用C ++類實際上有四個階段:

  1. 創建一個包含類聲明的頭文件
  2. 創建一個包含該類任何功能的C ++文件
  3. 從正在開發的C ++應用程序中調用標頭
  4. 編譯包含類功能和新應用程序的文件

這是正確的方法

Sales_item.h

#include <string>
#include <iostream>

class Sales_item {
 public:
     Sales_item(){};
     ~Sales_item(){};
          friend std::istream& operator>> (std::istream &in, Sales_item &si);
            friend std::ostream& operator<< (std::ostream &out, Sales_item &so);
private:
     std::string name;

};

std::istream& operator >> (std::istream &in, Sales_item &si)
{
     in >> si.name;
     return in;
}
std::ostream& operator << (std::ostream &out, Sales_item &so)
{
     out << so.name;
     return out;
}

main.cpp中

#include <iostream>
#include "Sales_item.h"
int main()
{
  Sales_item book;
  std::cin >> book;
  std::cout << book << std::endl;
  return 0;
}

來源: https : //sites.google.com/site/ypwangandy/tv

暫無
暫無

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

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