Code: Select all
// File: MyString.h
- - - - - - - - - - - - - -
#pragma once
// default includes with angular brackets
class LongNumber; // forward declaration
class MyString
{
char* symbols;
size_t capacity;
size_t length;
friend void LongNumber::Foo(MyString& str); //
// File: MyString.cpp
- - - - - - - - - - - - - -
// including "MyString.h" and "LongNumber.h" in .cpp to avoid circular dependency
#include "MyString.h"
#include "LongNumber.h"
// default includes with angular brackets
// Implementations
< /code>
// File: LongNumber.h
- - - - - - - - - - - - - -
#pragma once
// default includes with angular brackets
class MyString; // forward declaration
class LongNumber
{
uint8_t sign;
MyString digits;
void Foo(MyString& str); // supposed to be a friend to the class MyString
// Methods
}
< /code>
// File: LongNumber.cpp
- - - - - - - - - - - - - -
// including "MyString.h" and "LongNumber.h" in .cpp to avoid circular dependency
#include "MyString.h"
#include "LongNumber.h"
// default includes with angular brackets
void LongNumber::Foo(MyString& str) // supposed to be a friend to the class MyString
{
// some code
}
// other implementations
< /code>
File: Main.cpp
- - - - - - - - - - - - - -
#include
#include "MyString.h"
#include "LongNumber.h"
// #include "LongNumber.h"
// #include "MyString.h"
// reversed order won't help either
int main() {} // empty
< /code>
I have read about avoiding circular dependencies in C++. They advise you to forward declare the class in the .h
Code: Select all
// File: MyString.h
- - - - - - - - - - - - - -
#pragma once
// default includes with angular brackets
class UnknownClass; // forward declaration, deliberately wrote a name that does not exist
class MyString
{
char* symbols;
size_t capacity;
size_t length;
friend void UnknownClass::Foo(MyString& str); //
The error is the very same: ...MyString.h(11,28): error C2027: use of undefined type 'UnknownClass'
Ich habe das Gefühl, der einzige Weg, den Compiler zu informieren, dass die Klasse Longnumber abgeschlossen ist, besteht darin, #include "longnumber.h" in die Header -Datei einzulegen, aber das ist nicht erlaubt, weil es eine zirkuläre Abhängigkeit erzeugen würde.>