简体   繁体   中英

Accessing other abstract classes without including a reference in c++

I came across an old code in which there are few projects and each of them having few abstract classes, headers and cpp files. Strange thing is in one of the projects a abstract class makes use of a function declared in another abstract classs in the same project. What surprised me was there was no reference made to the other abstract class from the current abstract class and the compiler did not throw any error. Only thing I noticed was both files are in namespace.

Can anyone explain how is this possible?

Here are is a sample code of the class which is being referenced

#ifndef ClassADef
#define ClassADef

#include <string>

namespace globalNameSpace {
class ClassA {
public:

    virtual ~ClassA() = default;
    virtual std::string method1() const = 0;
};
}
#endif

Here is the sample code for the class which references the above class.

#ifndef ClassBDef
#define ClassBDef

#include <string>

//I was expecting an include statement which references the above class

namespace globalNameSpace {
class ClassB {
public:
    virtual std::string method2(const ClassA& method1, const bool variable) = 0; 
//I was expecting the compiler to throw an error.
};

}

#endif

只要在ClassB的定义之前向前声明ClassA,对ClassA的引用的使用似乎是有效的。

Besides the forward declaration or explicit include there could be another CPP file that includes both headers in the correct order:

#include <ClassADef>
#include <ClassBDef>

That is a bad practice, but that could explain the correctness of the code you provided.

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