【问题标题】:C++ How do i create a .h from a class cpp file [duplicate]C ++如何从类cpp文件创建.h [重复]
【发布时间】:2012-10-05 05:03:00
【问题描述】:

可能重复:
Regarding C++ Include another class

我是新手,想了解更多关于如何将我的 C++ 文件拆分为 .h 和 .cpp 的信息

这是我的 File2.cpp

#include <iostream>
#include <string>

using namespace std;

class ClassTwo
{
private:
string myType;
public:
void setType(string);
string getType();
};


void ClassTwo::setType(string sType)
{
myType = sType;
}

void ClassTwo::getType(float fVal)
{
return myType;
}

我想把它分成 2 个文件,即 .h 和 .cpp 我如何将其拆分为一个类,私有和公共。

我想在 File1.cpp(另一个 cpp 文件)中使用 ClassTwo

如何链接它以便在 ClassTwo 中使用它

感谢您的帮助。

【问题讨论】:

    标签: c++


    【解决方案1】:

    //文件2.h

    #include <iostream>
    #include <string>
    
    
    class ClassTwo
    {
    private:
       std::string myType;
    public:
       void setType(std::string);
       std::string getType();
    }; 
    

    //File2.cpp

    #include"File2.h"
    
    void ClassTwo::setType(std::string sType)
    {
        myType = sType;
    }
    
    std::string ClassTwo::getType()
    {
        return myType;
    } 
    

    //File1.cpp

    #include "File1.h"   //If one exists
    #include "File2.h"
    
    
    int main()
    {
        ClassTwo obj;
        return 0;
    }
    

    附带说明,我已经在您的 previous question here 上详细解释了这一点。
    你读过吗?

    【讨论】:

    • 我如何在 File1.cpp 中使用 ClassTwo,我是否在 File1.cpp 中包含“File2.h”或“File1.h”
    • @baokychen:我已经在上面的回答中给了你一个完整的例子。为什么你认为它没有回答你问的问题?你读过我对你之前的问题的回答吗?如果你这样做了,你就不会问问题了。
    • @Als - 您的示例有错字 - File1.cpp 的第 1 行应为 #include "File2.h"
    • @Robᵩ:糟糕,刚刚注意到。在您添加评论时已修复。实际上,我花了很多精力回答 OP 之前的 Q(请参阅内联链接以回答),其中包含很多细节,我很惊讶OP 又回来问同样的问题。
    • @Als,感谢您的回答。现在一切都已排序。
    【解决方案2】:

    我们可以继续讨论将文件分成 .cpp 和 .h/.hpp 所涉及的不同方面,但是,我认为此链接对您很有用:

    http://www.learncpp.com/cpp-tutorial/89-class-code-and-header-files/

    此外,您还需要避免“使用命名空间 std;”因为编译器不必要地加载了整个 C++ 标准命名空间。除此之外,这样做可能会无意中导致函数名冲突等。在实践中,只加载您将使用或将经常使用的标准命名空间中的内容。

    查看这里了解更多:

    Why is "using namespace std" considered bad practice?

    【讨论】:

      猜你喜欢
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      相关资源
      最近更新 更多