此代码似乎工作,但我不知道为什么:嵌套类构造函数调用私有构造函数,它工作吗?
#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)编译的,它似乎给了我期望的结果,但我不确定这是因为编译器是宽容的还是代码实际上是正确的。
为什么它似乎是Bar::Impl_()
可以调用Foo
构造函数时Foo
只结识Bar
而不是Bar::Impl_
?
我想我以前见过的多布斯博士的文章,我从中得到了外卖的是,你说的是只在C++标准的后续版本真的,不是严格的C++ 98 。但是,嘿,如果编译器对后来的标准支持足够普及,我会接受。 – jjramsey