【C++】类的私有成员遍历和公有成员变量
定义类:
#include <string> #include <iostream> using namespace std; //构造函数 定义对象的时候运行 //析构函数 定义的对象释放的时候运行 class girl { public: girl(); girl(double h, double w, int a, double s); ~girl(); private: double weight; int age; bool gz; public: int tellAge(); double tellWeight(); double height; double salary; }; girl::girl() { girl::height = 0.0; girl::weight = 0.0; girl::age = 0; girl::salary = 0.0; cout << "构造girl" << endl; gz = false; } girl::girl(double h, double w, int a, double s) { girl::height = h; girl::weight = w; girl::age = a; girl::salary = s; cout << "setAll2" << endl; gz = true; } girl::~girl() { cout << "析构girl" << endl; } int girl::tellAge() { if (gz) { return age; } else { cout << "没有初始值" << endl; return 0; } } double girl::tellWeight() { if (gz) { return weight; } else { cout << "没有初始值" << endl; return 0.; } }
类的使用
void main() { //girl Hua; girl Hua(180.0, 70.0, 20, 5000.0); girl Fua(170.0, 80.0, 25, 3000.0); //私有的成员不能直接访问,私有的类成员变量只能在类中访问 double ageTemp = Hua.tellAge(); cout << "Hua age is " << ageTemp << endl; double weightTemp = Hua.tellWeight(); cout << "Hua weight is " << weightTemp << endl; //公有的成员可以直接访问 cout << "Hua height is " << Hua.height << endl; cout << "Hua salary is " << Hua.salary << endl; cout << "Fua height is " << Fua.height << endl; cout << "Fua salary is " << Fua.salary << endl; cin.get(); }
类指针的使用
void main() { girl* Hua = NULL; Hua = new girl(180.0, 70.0, 20, 5000.0); //私有的成员不能直接访问,私有的类成员变量只能在类中访问 double ageTemp = Hua->tellAge(); cout << "Hua age is " << ageTemp << endl; double weightTemp = Hua->tellWeight(); cout << "Hua weight is " << weightTemp << endl; //公有的成员可以直接访问 cout << "Hua height is " << Hua->height << endl; cout << "Hua salary is " << Hua->salary << endl; delete Hua; Hua = NULL; cin.get(); }