class A;
class B
{
friend class A;
private:
int x;
public:
B(int x) {this->x = x;}
}
class A
{
friend class B;
private:
int x;
public:
A(int x) {this->x = x;}
}#pragma once
class B; // forward declaration
class A {
B *_b; // only reference or pointer to the incomplete type
public:
void a();
};#include "A.h"
#include "B.h"
void A::a() {
// Use this->_b
}#pragma once
class A; // forward declaration
class B {
A *_a; // only reference or pointer to the incomplete type
public:
void b();
};#include "B.h"
#include "A.h"
void B::b() {
// Use this->_a
}
Теперь же я подумываю...
Как сделать 2 класса дружественными друг другу (С++)?
Цель все так же - методы одного класса должны изменять поля другого.
#ifndef A_H
#define A_H
#include<iostream>
class B;
class A
{
friend class B;
public:
explicit A(int);
int getVal() const;
template<typename X>
void setVal(const X &x)
{
value = x.value;
}
void print()
{
std::cout << value << std::endl;
}
private:
int value;
};
#endif // A_H#ifndef B_H
#define B_H
#include<iostream>
class A;
class B
{
friend class A;
public:
explicit B(int);
int getVal() const;
template<typename X>
void setVal(const X &x)
{
value = x.value;
}
void print()
{
std::cout << value << std::endl;
}
private:
int value;
};
#endif // B_H#include "a.h"
A::A(int x) : value(x)
{
}#include "b.h"
B::B(int x) : value(x)
{
}#include "a.h"
#include "b.h"
int main()
{
A a(11);
B b(21);
B b2(31);
std::cout << "Before:\n";
a.print();
b.print();
std::cout << "After:\n";
b.setVal(a);
b.print();
a.setVal(b2);
a.print();
}