1.?class:即c++的类,与C语言的结构体相近,与结构体相比较,其成员不只有变量,还可以为函数,即类的成员函数,成员函数与普通函数区别在于其作用范围取决于类[1];通过类定义的内容叫做对象,详情见后续程序.
class类的程序:
#include <iostream>
using namespace std;
class Room {
public:
double length;
double width;
double height;
double Area(){
return length * width;
}
double Volume() {
return length * width * height;
}
};
int main() {
Room room1;
room1.length = 10.1;
room1.width = 9.9;
room1.height = 2.91;
cout << "Ares of room1=" << room1.Area() << endl;
cout << "Volume of room1=" << room1.Volume() << endl;
return 0;
}
2.构造函数的程序:
#include <iostream>
using namespace std;
class Student {
public:
double height;
const char* name;
Student(); //声明构造函数
Student(double, const char*);
};
Student:: Student() { //Student:: 用于指示此构造函数属于的类
this-> height = 171.1; //此函数没有参数,说明是一个默认构造函数,当创建一个新的Student对象时,会被自动调用
this-> name = "xiaoxia";
cout << "调用默认构造函数" << endl;
}
Student::Student(double height, const char* name) { //构造函数在类外面,必须在构造函数前面加上类名和作用域解析运算符(::)
this-> height =height ;
this-> name = name;
cout << "调用传递参数的函数" << endl;
}
int main() {
Student student1;//使用类Student定义一个对象student1
cout << student1.height << " " << student1.name << endl;
Student student2(171.9, "xiaoxichen");
cout << student2.height << " " << student2.name << endl;
return 0;
}
构造函数:主要用于初始化对象,没有返回值,名字与类同名,当创建类的对象时,会自动调用构造函数进行初始化;
注:类里面必须有构造函数,如果没有手动添加构造函数,则编译器会生成一个无参构造函数,该构造函数为空,不对类数据成员进行初始化操作,当创建该类的对象时,系统会使用这个默认的构造函数进行对象的初始化.
2.1构造函数也可以写到类里面:
#include <iostream>
using namespace std;
class Student {
public:
double height;
const char* name;
Student() { //Student:: 用于指示此构造函数属于的类
this-> height = 171.1; //此函数没有参数,说明是一个默认构造函数,当创建一个新的Student对象时,会被自动调用
this-> name = "xiaoxia";
cout << "调用默认构造函数" << endl;
}
Student(double height, const char* name) { //构造函数在类外面,必须在构造函数前面加上类名和作用域解析运算符(::)
this-> height =height ;
this-> name = name;
cout << "调用传递参数的函数" << endl;
}
};
int main() {
Student student1;//
cout << student1.height << " " << student1.name << endl;
Student student2(171.9, "xiaoxichen");
cout << student2.height << " " << student2.name << endl;
return 0;
}
参考: