2018/2/2
C++
1.关于友元关系
简单介绍:存在友元关系的两个类可以相互访问各自的访问级属性方法(public,protected,private)
实现代码:friend class name;
2.关于静态属性和静态方法
1.实现所需的一个或者多个方法和属性不属于类中某一个特殊的对象,而属于整个类
2.使得有关数据面向该类的所有对象
3.实现代码
#include<iostream>
#include<stdlib.h>
#include<string>
/*采用静态变量*/
using namespace std;
class Pet
{
public:
Pet(string TheName);//构造器
~Pet();//析构器
static int getcount();//接口
protected:
string name;
private:
static int count;
};
class Dog :public Pet//继承
{
public:
Dog(string TheName);//构造器
};
class Cat :public Pet//继承
{
public:
Cat(string TheName);//构造器
};
int Pet::count = 0;
Pet::Pet(string TheName)
{
name = TheName;
/*当使用默认构造器时,数量++*/
count++;
cout << "一只宠物诞生了,它的名字是:"<< name << endl;
}
Pet::~Pet()
{
count--;
cout << name << "挂了"<<endl;
}
int Pet::getcount()
{
return count;
}
Dog::Dog(string TheName) :Pet(TheName)
{
}
Cat::Cat(string TheName) :Pet(TheName)
{
}
int main()
{
Dog dog("JACK");
Cat cat("TOM");
/*使用静态方法*/
cout << "现在已经诞生了" << Pet::getcount() << "只宠物" << endl;
{
Dog dog2("micky");
Cat cat2("melee");
cout << "现在呢,已经诞生了" << Pet::getcount() << "只宠物" << endl;
}
cout << "现在还剩下" << Pet::getcount() << "只宠物" << endl;
system("pause");
}
注:1*对于private访问级的数据要被主程序读取时,可以设计一个接口便于读取数据(return);
2*注意构造器和析构器的使用,在主函数中采用{}确定作用域;