class A
{
public:
static void print()
{
cout<<"hello"<<endl;
}
};
class Test{
public static void print()
{
System.out.print("hello");
}
}
以上的代码都用 static修饰了一个函数。
1.static修饰的函数不能访问非static修饰的变量,这是C++和 JAVA都一样的。
2.不同的是 JAVA对 static 修饰的函数可以不创建对象,直接用类名调用,如:
public class Main {
public static void main(String[] args)
{
Test.print(); //here
}
}
class Test{
public static void print()
{
System.out.print("hello");
}
}
上述的JAVA代码,并没有创建对象,而是直接用 类名(Test)来调用 其static 方法。
这点C++是不允许的,C++必须先创建对象。