2012-08-15 258 views
0

如何限制從主函數訪問類函數?如何限制從主函數訪問類函數?

在這裏我的代碼。

class Bar 
{ 
public: void doSomething(){} 
}; 

class Foo 
{ 
public: Bar bar; 
//Only this scope that bar object was declared(In this case only Foo class) 
//Can access doSomething() by bar object. 
}; 

int main() 
{ 
    Foo foo; 
    foo.bar.doSomething(); //doSomething() should be limited(can't access) 
    return 0; 
} 

PS.Sry for my poor English。


編輯: 我沒有刪除舊的代碼,但我有新的代碼擴展。 我認爲這種情況下不能使用朋友類。因爲我計劃用於每個班級。由於

class Bar 
{ 
public: 
    void A() {} //Can access in scope that object of Bar was declared only 
    void B() {} 
    void C() {} 
}; 

class Foo 
{ 
public: 
    Bar bar; 
    //Only this scope that bar object was declared(In this case is a Foo class) 
    //Foo class can access A function by bar object 

    //main function need to access bar object with B, C function 
    //but main function don't need to access A function 
    void CallA() 
    { 
     bar.A(); //Correct 
    } 
}; 

int main() 
{ 
    Foo foo; 
    foo.bar.A(); //Incorrect: A function should be limited(can't access)  
    foo.bar.B(); //Correct 
    foo.bar.C(); //Correct 
    foo.CallA(); //Correct 
    return 0; 
} 

回答

4

FooBar

class Bar 
{ 
    friend class Foo; 
private: 
    void doSomething(){} 
}; 

的朋友,也避免成員變量public。使用setters/getters代替

1

您可以將Foo定義爲Bar的朋友類並使doSomething()爲私有。

1

製作Bar bar private在Foo會做的伎倆,不是嗎? 然後只有類Foo可以使用bar