【发布时间】:2021-11-12 12:43:34
【问题描述】:
我有 2 个类:S 和 R。R 有一个类型为 S 的实例。我想让 R 作为朋友类来访问 S 私有方法。 不幸的是,我无法构建它。请帮助我如何解决这个问题。我尝试了更多方式的前向声明,但没有奏效。我收到以下错误
R.hpp:12:15: error: ‘n1::n2’ has not been declared 12 | R(n1::n2::Sptr s);
提前非常感谢!
S.hpp:
#ifndef S_H
#define S_H
#include <memory>
namespace n1 {
namespace n2 {
class S {
friend class c1::R;
int x;
inline void print();
};
using Sptr = std::shared_ptr<S>;
}
}
#endif
S.cpp:
#include "S.hpp"
#include "R.hpp"
namespace n1 {
namespace n2 {
void S::print()
{
std::cout<<"S-print\n";
}
}
}
R.hpp:
#ifndef R_H
#define R_H
#include <memory>
namespace n1 {
namespace c1 {
class S;
struct R {
R(n1::n2::Sptr s);
void r();
n1::n2::Sptr s_;
};
}
}
#endif
R.cpp:
#include "R.hpp"
#include "S.hpp"
namespace n1 {
namespace c1 {
R::R(n1::n2::Sptr s):s_(s)
{}
void R::r() {
s_->print();
}
}
}
main.cpp:
#include <iostream>
#include "R.hpp"
#include "S.hpp"
#include <memory>
int main() {
auto s = std::make_shared<n1::n2::S>();
auto r = std::make_shared<n1::c1::R>(s);
r->r();
//s.print();
return 0;
}
【问题讨论】:
-
不清楚什么是 c1::R。 c1 在哪里声明?
-
R 在 n1::c1 命名空间中。