【发布时间】:2014-06-11 04:39:29
【问题描述】:
这段代码似乎可以工作,但我不知道为什么:
#include <iostream>
class Foo {
friend class Bar;
public:
void printNum() {std::cout << num_ << "\n";}
private:
// This constructor is private, should be accessible only to Bar
Foo(int num) : num_(num) {}
int num_;
};
class Bar {
public:
Bar(int num);
void printFooNum();
~Bar();
private:
class Impl_;
Impl_ * pImpl_;
};
struct Bar::Impl_ {
Impl_(int num);
Foo foo_;
};
Bar::Impl_::Impl_(int num)
: foo_(num)
{}
Bar::Bar(int num)
: pImpl_(new Impl_(num))
{}
void Bar::printFooNum() {
pImpl_->foo_.printNum();
}
Bar::~Bar() { delete pImpl_;}
int main() {
Bar bar(5);
bar.printFooNum();
return 0;
}
在这里,我试图确保 Foo 类的对象可以在 Bar 类的对象中构造,这是使用 pImpl 模式实现的。我实际上不介意构造函数Bar::Impl_() 显然能够调用Foo 构造函数,但我不确定为什么它应该起作用。这段代码是使用几种不同的编译器(GCC 和 Intel)编译的,它似乎给了我想要的结果,但我不确定这是因为编译器允许还是代码实际上是正确的。
为什么Foo 只与Bar 成为朋友而不是Bar::Impl_ 时,Bar::Impl_() 似乎可以调用Foo 构造函数?
【问题讨论】:
标签: c++ constructor friend