1.类
1 //创建类 2 class Person{ 3 4 //公共的属性 5 public: 6 void setAge(int age){ 7 this->age=age; 8 } 9 ~Person{} //析构函数 10 void setName(string name){ 11 this->name=name; 12 } 13 14 int getAge(){ 15 return this->age; 16 } 17 18 string getName(){ 19 return this->name; 20 } 21 //保护的属性 22 protected: 23 24 //私有的属性 25 private: 26 int age; 27 string name; 28 };
2.实例化对象
1 //实例化(创建对象) 2 Person p1; 3 p1.setAge(18); 4 p1.setName("zhangsan"); 5 cout << "age:" << p1.getAge() << ",name:" << p1.getName() << endl; 6 7 Person *p2 = new Person(); 8 p2->setAge(20); 9 p2->setName("lisi"); 10 cout << "age:" << p2->getAge() << ",name:" << p2->getName() << endl; 11 12 delete p2;//删除堆内存的对象
3.类的继承
1 //类的继承 2 class Student : public Person{ 3 public: 4 int cls; 5 };
4.继承实例化
1 Student s; 2 s.setAge(20); 3 s.setName("wangwu"); 4 s.cls=1; 5 cout << "age:" << s.getAge() << ",name:" << s.getName() << ",banji:" << s.cls <<endl;
5.函数重载(以构造方法重载为例)
返回值类型/参数类型/参数顺序不同的相同名字函数。
1 //创建类 2 class Person{ 3 public: 4 Person(){ 5 6 } 7 8 Person(int age){ 9 this->age=age; 10 } 11 12 int age; 13 };
实例化
1 Person *p1=new Person(); 2 p1->age=18; 3 cout << p1->age << endl; 4 5 Person *p2 = new Person(20); 6 cout << p2->age << endl;
6.命名空间
1 //创建命名空间 2 namespace A{ 3 int age=20; 4 } 5 6 //使用命名空间 7 using namespace A; 8 9 cout << A::age << endl;标签:p1,cout,int,age,C++,基础知识,Person,name From: https://www.cnblogs.com/qingfeng515/p/17526795.html