クラスのプライベートスコープはクラスのインスタンス化を妨げませんが、実際には「誰が」オブジェクトを作成できるかを制限します.
これは、外部からアクセスすることはできず、および他の `friend 関数とクラスに対してのみアクセスできる、プライベート スコープの他のメンバー データのようなものaccessorsですgetters。
#include <iostream>
using namespace std;
class Foo
{
public:
Foo(int x) : value(x){ cout << "Foo(int) public ctor" << endl;} // ctor
void SetValue(int x) {value = x;} // setter
int GetValue()const{return value;}// getter
private:
int value;
Foo(){ cout << "Foo() private ctor" << endl;} // private ctor
friend ostream& operator<<(ostream& out, Foo& rhs)
{
out << rhs.value;
return out;
}
friend Foo* CreateObject();
};
Foo* CreateObject()
{
Foo* ptrFoo = new Foo;
return ptrFoo;
}
int main ()
{
//Foo theFoo; // error C2248: 'Foo::Foo' : cannot access private member declared in class 'Foo'
Foo theFoo2(0); // ok
// cout << theFoo2.value << endl; // error C2248: 'value' : cannot access private member declared in class 'Foo'
cout << theFoo2.GetValue() << endl; // ok
cout << theFoo2 << endl;
Foo* ptrFoo = CreateObject();
ptrFoo->SetValue(7);
cout << ptrFoo->GetValue() << endl;
cout << endl;
return 0;
}