C语言面向结构,C++面向对象
栈对象生命周期函数体内部,堆对象生命周期可自己决定new的要自己delete。用new创建的是堆对象
#include <iostream>
using namespace std;
int main()
{
double r, h, v;
cin >> r >> h;
v = 3.14 * r * r * h;
cout << v << endl;//endl相当于换行
return 0;
}
public公有权限,private私有权限,protected保护权限
成员函数——成员方法;
访问权限一般原则:数据成员private;成员函数public;
#include <iostream>
using namespace std;
class Cup {
private:
double radius;
double height;
public:
//构造函数,以类的方式创建类对象,编译器自动调用构造函数完成变量初始化
Cup(double r, double h) {
radius = r;
height = h;
}
double getvolume()//普通成员函数,计算体积
{
return 3.14 * radius * radius * height;
}
};
int main() {
double r, h;
cin >> r >> h;
Cup c(r, h);//以类的方式构造类对象,栈对象
cout << c.getvolume() << endl;//打印输出并换行
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
public:
void set_data(int n, char *p,char s);
void display( );
private:
int num;
char name[20];
char sex;
};
void Student::set_data(int n, char *p,char s)//在类外进行了实现构造函数
{
num=n;
strcpy(name,p);
sex=s;
}
void Student::display( )
{
cout<<"num: "<<num<<endl;
cout<<"name: " <<name<<endl;
cout<<"sex: " <<sex<<endl<<endl;
}
int main()
{
Student stud1,stud2;
stud1.set_data(1,"He",'f');
stud2.set_data(2,"She",'m');
stud1.display();
stud2.display();
return 0;
}
访问对象中成员的一般形式 对象名.成员名
通过指针访问对象中的成员 p->show_time( );
#include <iostream>
using namespace std;
class Time
{
public:
Time() //类内定义构造函数
{
hour = 0;
minute = 0;
sec = 0;
}
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
void Time::set_time()
{
cin >> hour;
cin >> minute;
cin >> sec;
}
void Time::show_time()
{
cout << hour << ":" << minute << ":" << sec << endl;
}
int main()
{
Time t1;
t1.show_time();
Time t2;
t2.set_time();
t2.show_time();
return 0;
}
输入小时分钟秒,显示小时分钟秒
当以类的方式创建类对象时,初始化时自动调用构造函数。
构造函数不需要用户来调用它,而是在建立对象时自动执行。
构造函数的名字必须与类名同名,而不能由用户任意命名。
构造函数不具有任何类型,不返回任何值。
构造函数的功能是由用户定义的,用户根 据初始化的要求设计函数体和函数参数。
当对象生命周期结束时,需要释放内存空间时自动调用析构函数
析构函数的作用在撤销对象占用的内存之前完成一些清理、善后的工作。
只要对象的生命期结束,程序就自动执行事先设计好的析构函数来完成相关工作。
执行了几个构造函数,就要执行几次析构函数
QString字符串类型
#include <iostream>
using namespace std;
#include <string>
class Student
{
public:
Student(int n, string nam, char s)
{
num = n;
name = nam;
sex = s;
cout << "执行构造函数:" << name << " come." << endl;
}
~Student()
{
cout << "执行析构函数:" << "Bye bye, " << name << "." << endl;
}
void display();
private:
int num;
string name;
char sex;
};
void Student::display()
{
cout << "num: " << num << endl;
cout << "name: " << name << endl;
cout << "sex: " << sex << endl << endl;
}
int main()
{
Student stud1(10010, "Wang_li", 'f');
stud1.display();
Student stud2(10011, "Zhang_fun", 'm');
stud2.display();
return 0;
}
若提示name前的<<字符无法识别报错,解决办法添加头文件#include
#include <QApplication>
int main(int argc,char* argv[])
{
QApplication a(argc,argv);
return a.exec();
}