一:类的使用和类中基本的语法:
(1):在C++中,新的数据类型可以用class来构造,称为类类型。class声明的语法与C语言中的struct声明相似,但class中还可以包含函数声明。
1:类名(people) 对象名1(he),*对象名2(she); //she是一个类类型的指针。
2:类成员访问机制:私有成员,公有成员,保护成员。
3:构造函数,析构函数。
4:标准库类型;string。string s;表明创建一个string对象。string s = string y;把对象y拷贝给对象s。在这个过程会执行拷贝构造函数。(下一节)
构造函数:当一个对象被创建时,在C++中通过构造函数对对象进行初始化,即每当对象被声明或在堆栈中被分配或由new运算符创建时,
构造函数即被调用。
析构函数:析构函数是类的成员函数。它的名字与类名相同,只是在前面加了一个符号“~”。析构函数不接受任何参数,也不返回任何说明
的类型和值。
#include <iostream> #include <string> using namespace std;//using命名空间的空间的声明, /* run this program using the console pauser or add your own getch, system("pause") or input loop */ class people { public: people() { cout<<"输出无参数的构造函数"<<endl; this->other_people("no replay"); } people(string x,int y) { cout<<"输出有参数的构造函数"<<x<<endl; this->other_people(x); } ~people() //为什么会一直执行析构函数。 { cout<<"执行析构函数"<<endl; //delete this;// 为什么delete this的时候会进入死循环。:因为调用delete删除对象的时候会自动调用该类的析构函数. //也就是说,不需要你手动delete this,调用析构函数就是删除对象释放内存,不需要在手动添加delete函数。 } void read_other() { cout<<"other_people"<<this->other_peoples;//this代替的是当前对象. } private: int other_people(string s); //声明, 私有成员类外不能访问.除(友元类,友元函数) string other_peoples; }; int people::other_people(string s="没有告诉我对象叫什么名字") { this->other_peoples = s; cout<<"other_people"<<other_peoples<<endl; return 0; } int main(int argc, char** argv) { string s; cin>>s; //int g1,g2; //cin>>g1>>g2; //把第一个输入到g1第二个输入到g2。 //cout<<g1<<"and"<<g2<<endl; people big_people(s,4); return 0; }