03.C++类、this指针、static静态变量、构造函数、析构函数
2016-01-07 14:29
435 查看
Test.cpp文件:
Student.cpp文件
Student.h
#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 */
相关文章推荐
- 【c/c++】探寻C++最快的读取文件的方案
- 【c/c++】关键字typedef
- c++位运算
- C语言与木马恶意代码分析和360安全防护揭秘
- Sicily 1394. Root of the Problem
- C语言BT软件项目总结
- C++中传统枚举和强类型枚举的区别?
- C++左值与右值之道
- Effective C++ 条款44
- C++小题(十二)
- 【C++】:用sort对string类型进行排序
- 设计模式学习笔记c++版——单例模式
- POJ 1006_Biorhythms
- Sicily 1530. The Seven Percent Solution
- C语言设计ATM存取款界面
- C语言常用数学函数
- C++builder 图像字符流的存储和加载
- 【c/c++】STL标准入门汇总
- C++11多线程(十八):线程池
- C++操作Word学习笔记