时间记录:2024/1/6
类定义,一般在头文件中进行定义不进行实现,在源文件中进行实现
class Person{
public://公共属性和方法定义区Person();//构造函数定义~Person(){};//析构函数加实现int age;//定义属性void printAge();//定义方法
protected://保护属性和方法定义区
private://私有属性和方法定义区
};
方法实现
//构造函数实现
Person::Person()
{cout << "Person构造函数实现" <<endl;
}//普通方法实现
void Person::printAge()
{cout << this->age << endl;
}
创建对象进行使用
Person p;//创建实例化对象,保存在栈中p.age = 12;p.printAge();Person *p1 = new Person;//创建实例化对象,保存在堆中需要手动销毁p1->age = 15;p1->printAge();delete p1;//销毁对象
类的继承,子类继承基类可以使用基类中的方法和属性
创建子类继承Person类
class Student : public Person{
public:int age1;
};
创建子类对象,使用父类属性
Student s;s.age = 12;cout << s.age;
命名空间
namespace Test{//定义命名空间int age=50;void printAge();
}void Test::printAge()
{cout << age<<endl;
}
using namespace Test;//引入要使用的命名空间
进行使用命名空间,有点类似于C++中使用静态变量和函数
Test::age = 20;cout << Test::age << endl;Test::printAge();