main函数:
-
java 中当前运行的类是主类的时候调用
-
C++:
自由游离的函数,不定义在类内
#include<string>
#include<iostream>
using namespace std;
class Student
{
public:
Student(int n, string nam, char s)
{
num = n;
name = nam;
sex = s;
cout << "Constructor called." << endl;
}
~Student()
{
cout << "Destructor called." << endl;
}
void display()
{
cout << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "sex:" << sex << endl << endl;
}
private:
int num;
string name;
char sex;
};
int main()
{
Student stud1(10010, "Wang_li", 'f');
stud1.display();
Student stud2(10011, "Zhang_fang", 'm');
stud2.display();
system("pause");
return 0;
}
可以看出C++ 中的main函数相当于是调用函数的起点或者是入口,当然啦Java中也是吧。但是C++ 这个是写在类的外面,而Java就不是了。
类的声明
-
Java不需要在结尾的括号出加“;”
-
C++ 需要在结尾“;”
方法的调用
写法都相同
- Java是必须在类内部,且方法是以权限修饰符来限定的(public,protect,private),如果Java中方法没有写限定符,也就是不写,那么其方法是在这个包内可以调用。
- C++中类中可以写方法声明,也可以写方法实现,但是,方法声明后,在类外的实现需要用到作用域限定符" :: "
class Student
{
public:
void display();
private:
int num;
string name;
char sex;
};
void Student::display()
{
cout<<"num"<<num<<endl;
cout<<"name"<<name<<endl;
cout<<"sex"<<sex<<endl;
}
Student stu1,stu2;
如果函数作用于运算符前没有类名,或是既没有类名也没有作用域运算符如
::display()
或
display()
那么这就是一个全局函数,即普通函数。
类函数必须在类体中做原型声明,在类外定义实现。(C++中建议用这种写法)
静态方法和静态变量
静态方法写法都一样
Java可以用静态初始化块来初始化静态变量,不需要在源文件中声明
class Foo{
static private int x;
{
x=5;
}
}
对象的声明
- Java中:
- 总是在堆中声明的
MyTest test=new MyTest();
- 总是在堆中声明的
- C++中:
- 在栈中
MyClass test; - 在堆中
MyTest *test=new MyTest;
- 在栈中
继承
- Java中:
class Foo : public Bar
{
…
} - C++中:
class Foo extends Bar{
…
}
访问级别(主要是写法不同)
- Java:
public void f1();
public void f2();
- C++:
public :
void f1();
void f2();
内存管理
都用new 来分配,但是Java中不用delete,因为它有自己的垃圾回收机制
常量
- Java:
final int x=7; - C++
const int x=7;
数组
- Java:
int[] x = new int[10];
// 使用 x, 内存有垃圾回收器回收或
//或在程序生命周期尽头归还给系统
- C++:
int x[10];
//或
int *x = new x[10];
// 使用 x,然后归还内存
delete[] x;
集合和迭代器
-
Java:
迭代器只是一个接口,范围的开始是 <集合>.iterator,你必须用itr.hasNext()来查看是否到达集合尾。
ArrayList myArrayList = new ArrayList();
Iterator itr = myArrayList.iterator();
while ( itr.hasNext() )
{
System.out.println( itr.next() );
}
-
C++:
迭代器是类的成员。范围的开始是<容器>.begin(), 结束是 <容器>.end()。 用++ 操作符递增, 用 *操作符访问。
for (std::vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
{
*iter = 0; // set element to which iter refers to 0
}
抽象类
-
Java:
- abstract修饰符
abstract class Bar{ public void test(); }
- 接口
interface Bar{ public void test(); }
- 继承抽象类或实现接口
class Wine extends / implements Bar{ public void test(){ system.out.println("No beer!"); } }
-
C++:
只需要包含一个纯虚函数
class Bar{ public: virtual void foo()=0; }
引用与指针
- Java:
// 引用是可变的,仅存储对象地址;
// 没有指针类型
myClass x;
x.foo(); // error, x is a null ``pointer''
// 注意你要总是用 . 来访问域
- C++:
// 引用不可改变,通过使用指针来获得更多的灵活性
int bar = 7, qux = 6;
int& foo = bar;
编译
- Java:
// 编译foo.java文件中的类成<classname>.class javac foo.java
// 通过调用<classname>中的静态main方法来运行
java <classname>
- C++:
// 编译
g++ foo.cc -o outfile
// 运行
./outfile