# C++与java的异同

## 1. 基本数据类型：

C++有无类型void和宽字符型wchar\_t，java没有。

## 2. 运算符重载

不像java只能对方法进行重载，C++也支持对运算符进行重载，以实现Object的基本运算。比如：

```cpp
#include <iostream>

using namespace std;

//运算符重载
class Box {
private:
    int length;
    int width;
    int high;
public:
    int getLength() const {
        return length;
    }

    void setLength(int length) {
        Box::length = length;
    }

    int getWidth() const {
        return width;
    }

    void setWidth(int width) {
        Box::width = width;
    }

    int getHigh() const {
        return high;
    }

    void setHigh(int high) {
        Box::high = high;
    }

    //+运算符重载
    Box operator+(const Box& b){
        Box box;
        box.length = this->length + b.length;
        box.high = this->high + b.high;
        box.width = this->width + b.width;
        return box;
    }
};


int main ()
{
    Box box1, box2, box3;
    box1.setHigh(100);
    box1.setWidth(100);
    box1.setLength(100);

    box2.setWidth(200);
    box2.setHigh(200);
    box2.setLength(200);

    box3 = box1 + box2;
    cout << box3.getHigh() << "," << box3.getLength() << "," << box3.getWidth() << endl;
}
```

运行结果：

```
300,300,300
```

## 3. 模板template

C++中的模板类似java中的泛型。

## 4. 函数声明

在C++中函数必须先声明才能使用，一般把声明文件放在.h的头文件中。

## 5. 字符串定义

声明一个字符串有两种方式，一个是使用char数组，一个是使用string类型

```java
// 使用char数组定义字符串
char str1[3] = {'a', 'b', '\0'};//结尾必须加空字符标志\0，否则会被当成字符数组处理
char str2[] = "ab";//也可以这样定义，系统自动加上空白字符\0
// 使用string定义字符串
string c4 = "ab";
```

> 参考：
>
> 《C++ primer plus》
>
> <https://blog.csdn.net/u012485480/article/details/79592072>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jun-wang.gitbook.io/learnjava/bian-cheng-yu-yan/c++/c++-yu-java-de-yi-tong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
