如果仅存在私有函数,则访问基 class 中的私有数据类型
Access private data type in base class if only private function exist
给定下面的代码,如果 base 中的函数使用继承保护,我们可以访问 base class 的私有数据。我的问题是,如果 base class 中的所有方法也都设置为私有,我们是否可以通过任何方式访问私有数据?
class Base
{
int i;
protected:
void set(int data){
i = data;
}
int get(){
return i;
}
};
class derive: Base{
public:
void change(int x){
set(x);
cout<<get()<<endl;
}
};
int main()
{
derive b;
b.change(3);
return 0;
}
"we can access private data of base class if the function in base are protected by using inheritance",不,你并不是真的在访问私人数据。您正在为您执行此操作的基础 class 中调用 setter。不,你将无法调用你的基础 class.
的私有方法
在基 class 中将成员设置为私有将使其对所有子项也都是私有的。您可以定义新的 public 函数来更改子项中的这些成员。
通过使用 friend
使 derive class 成为 Base
的朋友
class derive;//forward declaration
class Base
{
int i;
private:
void set(int data){
i = data;
}
protected:
int get(){
return i;
}
public:
friend class derive;
};
class derive : public Base{
public:
void change(int x){
set(x);
cout<<get()<<endl;
}
};
您应该了解 public/protected 继承。 class a : public/protected b
不使用访问说明符overloading/overriding:
- C++: overriding public\private inheritance
- http://www.learncpp.com/cpp-tutorial/116-adding-changing-and-hiding-members-in-a-derived-class/
现在我将展示如何重新声明继承成员的访问说明符:
class derive : public Base{
public:
Base::set;//this is valid redeclaration within public scope. Now anybody could use derive::set(x)
void change(int x){
set(x);
cout<<get()<<endl;
}
}
给定下面的代码,如果 base 中的函数使用继承保护,我们可以访问 base class 的私有数据。我的问题是,如果 base class 中的所有方法也都设置为私有,我们是否可以通过任何方式访问私有数据?
class Base
{
int i;
protected:
void set(int data){
i = data;
}
int get(){
return i;
}
};
class derive: Base{
public:
void change(int x){
set(x);
cout<<get()<<endl;
}
};
int main()
{
derive b;
b.change(3);
return 0;
}
"we can access private data of base class if the function in base are protected by using inheritance",不,你并不是真的在访问私人数据。您正在为您执行此操作的基础 class 中调用 setter。不,你将无法调用你的基础 class.
的私有方法在基 class 中将成员设置为私有将使其对所有子项也都是私有的。您可以定义新的 public 函数来更改子项中的这些成员。
通过使用 friend
使 derive class 成为 Base
class derive;//forward declaration
class Base
{
int i;
private:
void set(int data){
i = data;
}
protected:
int get(){
return i;
}
public:
friend class derive;
};
class derive : public Base{
public:
void change(int x){
set(x);
cout<<get()<<endl;
}
};
您应该了解 public/protected 继承。 class a : public/protected b
不使用访问说明符overloading/overriding:
- C++: overriding public\private inheritance
- http://www.learncpp.com/cpp-tutorial/116-adding-changing-and-hiding-members-in-a-derived-class/
现在我将展示如何重新声明继承成员的访问说明符:
class derive : public Base{
public:
Base::set;//this is valid redeclaration within public scope. Now anybody could use derive::set(x)
void change(int x){
set(x);
cout<<get()<<endl;
}
}