---
title: "3、c++中的类"
author: "nickfover"
date: "2014-10-11T16:03:20Z"
tags: []
categories: ["开源软件"]
slug: "3-c"
draft: false
lastmod: "2014-10-11T20:16:14Z"
id: 2128547
url: "https://nickfover.iteye.com/blog/2128547"
---

c++中的类和java中定义一样，类是用户定义的一种(元)数据类型，类包含数据和方法，类与实例的关系 就像 基本数据类型如int 与x的关系，x是整形具有数字相关的操作；cout和cin是iostream的实例(java中讲实例和方法，c++讲对象和函数，其实是一样的；具体cout是ostream，cin是istream的实例)；

函数原型：

函数声明由函数返回类型、函数名和参数列表组成。参数列表必须包括参数类型,但不必包含具体类型实例。这三个元素被称为函数原型,函数原型描述了函数的接口。

 

函数原型类似函数定义时的函数头，又称函数声明。为了能使函数在定义之前就能被调用，C++规定可以先说明函数原型，然后就可以调用函数。函数定义可以放在主函数后面。 由于函数原型是一条语句，因此函数原型必须以分号结束。函数原型由函数返回类型、函数名和参数表组成，它与函数定义的返回类型、函数名和参数表必须一致。函数原型必须包含参数的标识符（对函数声明而言是可选的）；

 

函数原型fun(double)；函数定义fun(double x);

使用库方法，要添加相应的头文件，如何写一个自己的方法，跟java里类似，但要在main()函数前添加函数原型；函数原型描述了函数接口，

 

```
#include <iostream.h>
int myFirstFunction(int);
int main()
{
	int x;
	x= myFirstFunction(4);
	cout<<"this value : "<<x<<endl;
	cout<<"this value : "<<myFirstFunction(0)<<endl;  //可以直接调用方法返回值
	return 0;
}
int myFirstFunction(int x){
return x= x+100;
}
```

从前面的几个例子中，main函数都有int返回值，java中中main方法是不能有返回值的，在c++中，也可以使void的，声明为int型，那这个返回值会被谁调用呢？

 

可以将计算机操作系统作为调用程序，main()返回值交给了操作系统，约定返回值为0表示程序运行成功，非0表示存在问题；

 

查看一个变量的内存地址：

 

```
#include <iostream.h>
int main()
{
	int x;
	x= 4;
	cout<<"this parameter memory address : "<<&x<<endl;
	return 0;
}
```

 输出：this parameter memory address : 0x0018FF44

 

 

```
short int              带符号2字节短整形 - 32768 ~ 32767
unsigned int       无符号4字节整形   0 ~ 2^32 -1  
```

 

c++的String与java的String不一样；c++本身没有对String类型封装；

c++中 char hello\[5] = "hello";  //这样会保错，因为这是字面赋值方式，会在hello后面加个\\0，变成6个字符；

使用char hello\[5]={'h','e','l','l','0'};不会报错；但在打印时多出两个汉字：烫虉  若改为6就没事了；

使用 char hello\[6] = "hello"; 不会报错；

 

通过cin来读取String：

char x\[7];

 

cin&gt;&gt;x;   

若这样输入 he lloooo   只会读取前两个字符he，若输入hellooo程序运行时出错；

如何将he llo正确读入：cin.getline(hello,7):

```
#include <iostream.h>
int main()
{
	char hello[7];
	cin.getline(hello,7);//将输入的字符赋值给hello；
	cout<<hello;
	return 0;
}
```

输出：

he llo

he lloPress any key to continue

若执行：

```
        cout<<"ok";
	char hello[7];
	cin.getline(hello,7);//将输入的字符赋值给hello；
	cout<<"hello"<<hello<<endl;
	return 0;
```

 输出为：

ok\[回车]

hello

而没有执行输入；因为cin将回车键当做空字符输入，这样会导致运行不明确，可以修改为：

```
	cout<<"ok";
	char hello[7];
	cin.get();  //添加一个无返回的空接收
	cin.getline(hello,7);//将输入的字符赋值给hello；
	cout<<"hello"<<hello<<endl;
	return 0;
```

c++的String是用string ；并添加&lt;string&gt;不是&lt;string.h&gt; 或&lt;cstring&gt;

```
#include <iostream>
#include <string>
int main()
{
	using namespace std;
	string s;
	s = "ok";
	cout<<s+"\"skx\"";
	return 0;
}
```

 字符数组的赋值和追加：要添加头文件。

```
#include <iostream>
#include <string>
#include <cstring>
int main()
{   
	using namespace std; 
	char a[3]="ok";
	char b[3];
	char c[6] = "世界";
	strcpy(b,"ok");
	strcat(b,c);
	cout<<b<<endl;
	return 0;
}
```

 上面b的长度声明为3，实际打印出来更长，这样可能出现异常，c++提供了两个相对安全的方法：strncpy和strncat;