// 下面我们通过简单的例子来说明构造函数和析构函数的使用#include<iostream>#include<string>
using namespace std;
class Dog {
public:Dog();~Dog();};intmain(){
Dog dog;
cout<<"构造与析构函数示例"<<endl;return0;}// 类的函数可以在类里实现,也可以在类外实现,不过在类外实现时需要使用“::”
Dog::Dog(){
cout<<"构造函数执行!"<<endl;}// 类的析造函数定义在类的外面
Dog::~Dog(){
cout<<"析构函数执行!"<<endl;}
3-1-2:this 指针
每个对象都拥有一个 this 指针,this 指针记录对象的内存地址。 在 C++中,this 指针是指向类自身数据的指针,简单的来说就是指向当前类的当前实例对象
关于类的 this 指针有以下特点
1:this 只能在成员函数中使用,全局函数、静态函数都不能使用 this
2:this 在成员函数的开始前构造,在成员函数的结束后清除
3:this 指针会因编译器不同而有不同的放置位置。可能是栈,也可能是寄存器,甚至全 局变量
#include<iostream>#include<string>
using namespace std;
class Dog {
public:
string name;voidfunc();};intmain(){
Dog dog;
dog.func();return0;}void Dog::func(){// 在类的成员函数里使用了 this 指针,并指向了类里的成员 name。// 先将 name 赋值叫“旺财”,然后我们打印 name 的值。
this->name ="旺财";
cout<<"小狗的名字叫:"<<this->name<<endl;}
#include<iostream>#include<string>
using namespace std;
class Dog
{
public:
string name;voidgetWeight(int weight){
cout<<name<<"的体重是:"<<weight<<"kG"<<endl;}voidgetWeight(double weight){
cout<<name<<"的体重是:"<<weight<<"kG"<<endl;}};intmain(){
Dog dog;
dog.name ="旺财";
dog.getWeight(10);
dog.getWeight(10.5);return0;}
3-3-2:运算符重载
#include<iostream>#include<string>
using namespace std;
class Dog
{
public:int weight;
Dog operator+(const Dog &d){
Dog dog;
dog.weight = this->weight + d.weight;return dog;}};intmain(){
Dog dog1;
Dog dog2;
Dog dog3;
dog1.weight =10;
dog2.weight =20;
dog3 = dog1 + dog2;// ,重载运算符“+”,可以把两个对象进行相加。// 在普通的算术运算符“+”是不能将两个对象进行相加的,所以我们重载运算符的意义可以体现在这里
cout<<"第三只狗的体重是:"<<dog3.weight<<endl;return0;}
#include<iostream>#include<string>
using namespace std;
class Dog
{
public:
string name;Dog(int i =0){
total = i;}voidaddFood(int number){
total = total + number;}intgetFood(){return total;}// 通过2个函数对私有变量进行操作
private:int total;};intmain(){
Dog dog;
dog.name ="旺财";
dog.addFood(3);
dog.addFood(2);
cout<<dog.name<<"总共获得了"<<dog.getFood()<<"份食物"<<endl;return0;}