您的位置:首页 > 编程语言 > C语言/C++

03.C++类、this指针、static静态变量、构造函数、析构函数

2016-01-07 14:29 435 查看
Test.cpp文件:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

#include"Student.h"

int main() {

Student stu("啦",20);
stu.say();
Student stu2("laixiao", 20);
stu2.say();

//使用复制构造函数
Student stu3(stu);
stu3.say();

return 0;
}


Student.cpp文件

#include<iostream>
#include<string>
#include<vector>
using namespace std;

#include"Student.h"

void Student::say()
{
cout << myName << myAge << endl;
}

void Student::setAge(int age)
{
this->myAge = age;//使用this指针,代表当前对象。
}

void Student::setName(string name)
{
myName = name;
}

int Student::getAge()
{
return myAge;
}

string Student::getName()
{
return myName;
}

Student::Student()
{
myAge = 20;
myName = "laixiao赖总";
phone = phone + 1;
}

Student::Student(string name, int age)
{
myName = name;
myAge = age;
}

Student::Student(Student & stu)
{
myName = stu.myName;
myAge = stu.myAge;
}

Student::~Student()
{
cout << "析构函数被执行" << endl;
}

int Student::phone = 0;


Student.h

#ifndef STUDENT_H
#define STUDENT_H

#include<iostream>
#include<string>
#include<vector>
using namespace std;

//1.C++允许使用struct定义一个类
class Student {
public:

void setAge(int age);
void setName(string name);
int getAge();//类中声明,类外定义。
string getName();

Student();//无参构造函数
Student(string name,int age);//有参构造函数
Student(Student& stu);//复制构造函数
~Student();//析构函数

void say();

private:
int myAge;
string myName;
static int phone;//静态整型变量(同java)
};

#endif

/*
作用:防止重复包含
开头处:
#ifndef STUDENT_H
#define STUDENT_H

结尾处:
#endif
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: