1 结构体
在C语言中我们可以定义结构体,将多个相关的变量包装在一块整体使用。这些变量可以是完全不同的数据类型。但是在C语言中结构体不能包含函数。
在面向对象的程序设计中,对象具有状态(属性)和行为,属性保存在成员变量中,行为通过成员函数来实现。这样在C语言中结构体只能描述一个对象的状态,不能实现它的行为。因此C++对其进行了扩展,在C++结构体中可以包含函数。
1.1 结构体的定义
#include <iostream>
using namespace std;
struct student
{
char* name;
int age;
};
void main(){
student stu;
stu.name = "FreeBamb";
stu.age = 20;
cout << stu.name << endl << stu.age << endl;
system("pause");
}
输出结果:
说明:C++中预定义的三个标准输入输出流对象:
cin与出入操作符(>>)一起用于从标准输入读入数据,
cout与输出操作符(<<)一起用于输出数据到标准输出,
cerr与输出操作符(<<)一起用于输出错误信息到标准错误上。
cin和cout的使用比C语言中的scanf和printf要简单的多,不用考虑输入输出的数据类型。
注意:(1)用了endl(end of line)表示换行,最后一个是字母l不是数字1,相当于C语言中的'\n';
(2)在定义结构体时,一定不要忘了在右括号出加上一个分号(;)
c++结构体中定义函数事例:
#include <iostream>
using namespace std;
struct student
{
char* name;
int age;
void output(){
cout << name << endl << age << endl;
}
};
void main(){
student stu;
stu.name = "FreeBamb";
stu.age = 20;
//cout << stu.name << endl << stu.age << endl;
stu.output();
system("pause");
}
输出结果:
2 结构体与类
将上面的关键字struct换成class。类和结构的定义除了使用关键字class和struct不同之外,更重要的是成员访问控制也不相同,结构体默认情况下,其成员是公有的(public),类默认情况下,其成员是私有的(private),因此需要访问类中的成员时需要定义其访问控制权限为public代码如下所示。
#include <iostream>
using namespace std;
class student
{
public:
char* name;
int age;
void output(){
cout << name << endl << age << endl;
}
};
void main(){
student stu;
stu.name = "FreeBamb";
stu.age = 20;
//cout << stu.name << endl << stu.age << endl;
stu.output();
system("pause");
}
输出结果: