什么是面向对象程序语言
面向对象语言的主要特征
什么是类,对象和成员
声明一个类
#include<iostream>
using namespace std;
//声明一个类
class Human
{
public:
void GetStature();
void GetWeight();
private:
int stature;
int weight;
};
int main()
{
}
#include<iostream>
using namespace std;
//声明一个类
class Human
{
public:
void GetStature()
{
cout<<stature;
}
void SetStature(int x)
{
stature=x;
}
void GetWeight();
void SetWeight(int x);
private:
int stature;
int weight;
};
void Human::GetWeight()
{
cout<<weight;
}
void Human::SetWeight(int x)
{
weight=x;
}
int main()
{
Human Mike;
Mike.SetStature(8);
cout<<"麦克的身高";
Mike.GetStature();
cout<<endl;
Mike.SetWeight(80);
cout<<"麦克的体重";
Mike.GetWeight();
}
公有和私有
#include<iostream>
using namespace std;
class Human
{
public:
void set(int w)
{
if(w>0&&w<100)
{
weight=w;
}
else
{
cout<<"请将set函数设置为一个大于0而小于100的数字,否则默认返回0"<<endl;
weight=0;
}
}
int show()
{
return weight;
}
private:
int weight;
};
int main()
{
Human Tom;
Tom.set(90);
cout<<"汤姆的体重为: "<<Tom.show()<<"\n";
Human Mike;
Mike.set(80);
cout<<"迈克的体重为: "<<Mike.show()<<"\n";
return 0;
}
内联函数
#include<iostream>
using namespace std;
class A
{
public:
inline void print(int);
int get()
{
return x;
}
private:
int x;
};
//inline int print(int);//声明内联函数
void A::print(int a)
{
x=a;
}
int main()
{
A a;
int x;
cout<<"请输入一个数字\n";
cin>>x;
a.print(x);
cout<<"\n";
cout<<"输入的数字为: "<<a.get()<<endl;
return 0;
}
析构函数
#include<iostream>
using namespace std;
class A
{
public:
A();
~A();
//构造函数
/*A()
{
cout<<"构造函数执行完毕!\n";
}*/
//析构函数 一个类只能有一个析构函数
/*~A()//析构函数不能有参数,无返回值
{
cout<<"析构函数执行完毕!\n";
}*/
};
A::A()
{
cout<<"构造函数执行完毕!\n";
}
A::~A()
{
cout<<"析构函数执行完毕!\n";
}
int main()
{
A a;
return 0;
}