简体   繁体   中英

How to inherit c++ header file?

In java there is no header file. We import Class and use function. We can also extend them. In C++ there is header file. We include them and use function. Now my question, how to inherit them like java extends and is it possible?

Every program has its own way of doing something. In c++ you can do like:

//filename foo1.h
class foo1{
}

Now inn another file say foo2.h

//filename foo2.h

    #include "foo1.h"
    class foo2 : public foo1
    {
    }

Java combines two things which C++ separates: the class definition and the definition of its members.

Java:

class Example {

    private String s;

    protected static int i = 1;

    public void f() {
        System.out.println("...");
    }

    public Example() {
        s = "test";
    }
}

C++ class definition:

class Example
{
private:
    std::string s;

protected:
    static int i;

public:
    void f();
    Example();
};

C++ definition of members:

int Example::i = 1;

void Example::f()
{
    std::cout << "...\n";
}

Example::Example() :
    s("test")
{
}

The separation into *.h and *.cpp files is purely conventional . It typically makes sense to put the class definition into the *.h file and the definition of the members into the *.cpp file. The reason why it makes sense is that some other code using the class only needs the class definition , not the definition of its members. That "other code" includes subclasses. By providing the class definition in a separate file, a user of the class can just #include the header and doesn't need to bother with the *.cpp file.

(Note that the *.cpp file, too, needs to #include its corresponding header file.)

If that looks complicated to you, view it from a different perspective. It allows you to modify the definition of the members without users of your class having to recompile their code. This is a big advantage of C++ compared to Java! The larger your project, the more important an advantage it becomes.

在具有继承/多态性的 c++ 中执行此操作的一般方法是声明以下内容:

#include "myheaderfile.h"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM