问题一:超前使用
java不分先后,其所有的东东都得在类里面,所以没有声明与定义之分
问题二:对象作用域与生命期
对象都是在堆上分配的,内置类型(基本类型)是在栈分配空间
下面C++代码:
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
会导致程序崩溃同样在java:
public class TestS { void getUnit(TestUnit tt){
tt = new TestUnit();
} public static void main(String[] args) {
TestS s = new TestS();
TestUnit t = null;
s.getUnit(t);
t.print();
}
}
class TestUnit {
void print(){
System.out.println("TestUnit");
}
}
以上程序也会出现异常:java.lang.NullPointerException
但是可以换种方式用return来返回一个对象的引用

解决方案 »

  1.   

    我按你的说法把上面的程序改了如下:(结果确实如您所说,但前后两个程序有什么本质区别呢?帮忙解释详细点。谢谢!)
    public class TestS { TestUnit getUnit(){
    return new TestUnit();
    } public static void main(String[] args) {
    TestS s = new TestS();
    TestUnit t = null;
    t=s.getUnit();
    t.print();
    }
    }
    class TestUnit {
    void print(){
    System.out.println("TestUnit");
    }
    }
      

  2.   

    c++中有同样的问题:您给的那个例子会出现内存引用出错,下面的就没有问题
    #include <stdio.h>
    #include <string.h>
    #include <malloc.h>
    char * GetMemory()
    {
     return (char *)new char[100];
    }
    void Test(void)
    {
    char *str = NULL;
    str=GetMemory();
    strcpy(str, "hello world");
    printf(str);
    }
    void main()
    {

    Test();
    }
      

  3.   

    谢谢!
    我有一种新的方法改写您给的c++例子,这样就不会有问题了。
    #include <stdio.h>
    #include <string.h>
    #include <malloc.h>
    void GetMemory(char* &p)
    {
      p = (char *)malloc(100);
    }
    void Test(void)
    {
    char *str = NULL;
    GetMemory(str);
    strcpy(str, "hello world");
    printf(str);
    free(str);
    }void main()
    {
    Test();
    }