//C++语言 通过构造函数初始化学生信息 #include "stdafx.h" #include <iostream> #include <string> using namespace std; /* class CStudent { private: char m_Name[10]; int m_Age; double m_Height; public: CStudent(char *name, int age, double height) { strcpy(m_Name, name); m_Age = age; m_Height = height; } void display() { cout << "name:" << m_Name << endl; cout << "age:" << m_Age << endl; cout << "height:"<< m_Height << endl; } }; */ /* //内联函数 class CStudent { private: char m_Name[10]; int m_Age; double m_Height; public: CStudent(char *name, int age, double height); inline void display(); }; CStudent::CStudent(char *name, int age, double height) { strcpy(m_Name, name); m_Age = age; m_Height = height; } inline void CStudent::display() { cout << "name:" << m_Name << endl; cout << "age:" << m_Age << endl; cout << "height:"<< m_Height << endl; } int main(int argc, int argv[]) { CStudent student("格格", 18, 160); student.display(); //内联函数 return 0; } */ /* //友元函数 class CStudent { private: char m_Name[10]; int m_Age; double m_Height; public: CStudent(char *name, int age, double height); friend void display(CStudent &stu); }; CStudent::CStudent(char *name, int age, double height) { strcpy(m_Name, name); m_Age = age; m_Height = height; } void display(CStudent &stu) { cout << "name:" << stu.m_Name << endl; cout << "age:" << stu.m_Age << endl; cout << "height:"<< stu.m_Height << endl; } int main(int argc, int argv[]) { CStudent student("格格", 18, 160); display(student); //友元函数 return 0; } */ class CStudent { private: char m_Name[10]; static int m_Age; //声明静态成员变量 static double m_Height; //声明静态成员变量 public: CStudent(char *name, int age, double height); static void SetStu(int age, int height); //声明静态成员函数 static void display(); //声明静态成员函数 }; CStudent::CStudent(char *name, int age, double height) { strcpy(m_Name, name); m_Age = age; m_Height = height; } void CStudent::SetStu(int age, int height) { m_Age = age; m_Height = height; } void CStudent::display() { //cout << "name:" << m_Name << endl; //静态成员函数不可以访问普通成员变量 cout << "age:" << m_Age << endl; cout << "height:"<< m_Height << endl; } //初始化静态成员变量 ##不能用参数初始化表,对静态成员变量进行初始化 int CStudent::m_Age = 0; double CStudent::m_Height = 0; int main(int argc, int argv[]) { CStudent::display(); //显示初始化的值 CStudent student("格格", 18, 160); student.display(); CStudent::SetStu(24, 170); student.display(); return 0; }