c++中访问修饰符有:public protected private
java中有:public protected default private
c++中:当类中成员变量有protected修饰时,该类的对象是不能直接访问该成员变量的,只有在该类和子类中访问,
这与java不同!
举例如下:
public class Test {
protected void fun(){
System.out.println("hello");
}
public static void main(String[] args) {
Test t=new Test();
t.fun();
}
}
protected void fun(){
System.out.println("hello");
}
public static void main(String[] args) {
Test t=new Test();
t.fun();
}
}
java中编译通过打印出hello
#include <iostream>
#include <math.h>
using namespace std;
class A
{
protected:
void fun()
{
cout<<"hello"<<endl;
}
};
int main(){
A a;
a.fun();
return 0;
}
c++中则报错error C2248: 'fun' : cannot access protected member declared in class 'A'
#include <math.h>
using namespace std;
class A
{
protected:
void fun()
{
cout<<"hello"<<endl;
}
};
int main(){
A a;
a.fun();
return 0;
}
c++中则报错error C2248: 'fun' : cannot access protected member declared in class 'A'