C++ 友元 ,常量,静态成员
//头文件 #ifndef STUDENT_H #define STUDENT_H class Student { public: friend void Print_Student(); //友元声明 Student(const int m_student_id,const char* m_student_name);//带参构造 Student(const Student& other); //拷贝构造 private: void printStudentInfo();//输出学生信息 void SetStudentName(const char* m_student_name); //设置学生姓名 static int School_Id; //定义学校id const int StudentId; //定义学生id char* StudentName;//定义学生名称 }; int Student::School_Id = 1; //类中的静态成员需要在类外初始化 void Print_Student(); #endif
//cpp文件
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "Student.h" using namespace std; //带参构造 Student::Student(int m_student_id, const char* m_student_name) :StudentId(m_student_id) { this->StudentName = new char[strlen(m_student_name) + 1]; strcpy(this->StudentName, m_student_name); } //拷贝构造 Student::Student(const Student& other) :StudentId(other.StudentId) { this->StudentName = new char[strlen(other.StudentName) + 1]; strcpy(this->StudentName, other.StudentName); } //打印学生信息 void Student::printStudentInfo() { cout << "学校id:" <<School_Id<< "\t学生学号id:"<<StudentId << "\t学生姓名:"<<StudentName << endl; } //设置学生姓名 void Student::SetStudentName(const char* m_student_name) { strcpy(this->StudentName, m_student_name); } void Print_Student() { Student temp1(1, "小明"); temp1.printStudentInfo(); //打印学生1的信息 temp1.SetStudentName("小刚"); Student temp2(temp1); temp2.printStudentInfo();//打印学生2的信息 } int main() { Print_Student(); return 0; }