问题一:超前使用
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来返回一个对象的引用
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来返回一个对象的引用
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");
}
}
#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();
}
我有一种新的方法改写您给的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();
}