So I am coding a program in c , I got a version of the program that returns the same error:
#include <iostream>
class A
{
public:
B foo()
{
return B();
}
};
class B
{
public:
A bar()
{
return A();
}
};
int main(int argc, char const *argv[])
{
A x = A();
B y = x.foo();
return 0;
}
But whenever I compile it, it gives me two errors:
main.cpp:6:5: error: unknown type name 'B'
B foo()
^
main.cpp:8:16: error: use of undeclared identifier 'B'
return B();
However I can't just move B above A because I will just get a different error:
main.cpp:6:5: error: unknown type name 'A'
A bar()
^
main.cpp:8:16: error: use of undeclared identifier 'A'
return A();
I am completely stumped on how to solve this so any help would be appreciated!
CodePudding user response:
You need to split declaration and definition. Also, you need to declare B as a class before A uses it.
#include <iostream>
class B;
class A {
public:
B foo();
};
class B {
public:
A bar();
};
B A::foo() {
return B();
}
A B::bar() {
return A();
}
int main(int argc, char const *argv[]) {
A x = A();
B y = x.foo();
return 0;
}