c++ - 在 C++ 中定义一个类

标签 c++ class error-handling

当我尝试运行这个程序时,我收到一条错误消息:

"fatal error: sales_item.h: No such files or directory.

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

这是什么意思?我读的书,c++ primer 5th edition,教我用这种方式定义一个类。 这是错的吗? 为什么我不能运行这个程序?

最佳答案

是的,这是错误的。

假设此代码位于名为 MyFile.cpp 的文件中,那么您的代码片段假定类的声明位于文件 "Sales_item.h" 在与 MyFile.cpp 源文件相同的文件夹中。

#include其实是一个copy/paste指令,将指定文件的内容复制到当前文件中,由编译器编译。现在 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++ - 在 C++ 中定义一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16706404/

相关文章:

c++ - 信号/槽与直接函数调用

java - 当我将监听器传递给异步任务时出现类转换错误

javascript - 如何将调用者详细信息添加到 Node.js 中的错误堆栈跟踪中?

php - getmxrr 和弃用的 : Call-time pass-by-reference

c++ - 编译器如何知道为每个静态变量调用一次函数?

c++ - boost 目录迭代器错误 : no match for operator! =

c++ - 是否可以在未安装 CUDA 驱动程序的情况下运行 CUDA 程序或库?

class - 如何在 Laravel 5 中添加我自己的自定义类?

java - 如何将方法包装在异步代码部分周围

error-handling - 如何应对 "disk full"方案?