cpp:变量的定义与Java中的不同

来源:互联网 发布:怎样在淘宝查注册时间 编辑:程序博客网 时间:2024/05/21 10:40

Java中,除了基本类型的变量,任何变量在定义之后,使用之前,必须先进行赋值,否则调用时就会抛出空指针异常,而对于基本类型的变量,如果是函数内变量,必须赋值,否则编译报错。

c++中,函数内定义的任何变量,系统都会自动分配内存单元,也就是说,可以不进行赋值,而直接调用。

比如,下面的代码,在c++中是正常合法的代码,但是在java中就会抛空指针异常:

#include <iostream>#include <string>using namespace std;struct student {    std::string name;    int age;};int main() {    string str;    unsigned long size = str.size(); // c++中ok ,java 中就会报空指针异常    cout << "str=" << str << " , size=" << size << " , " << sizeof(str) << endl;    cout << "# # # # # # # # # " << endl;    student kelly;    cout << kelly.name << " , " << kelly.age << sizeof(kelly) << endl; // ok,java中会报空指针    cout << "-- # # # # # # # # # " << endl;    student *rose = new student;    cout << (*rose).name << " , " << (*rose).age << sizeof(*rose) << endl;    delete rose;    return 0;}

这个区别特别重要,不然对于Java程序员,去看C++的代码,老是感觉C++有膜法,不清楚什么时候需要mallooc/new

ps:对于数组,c++也其他变量一样,声明了就能使用,不需要主动去new。

原创粉丝点击