成員函式——“this指標”
阿新 • • 發佈:2018-11-10
#include <iostream> class A { static int a; int b; public: //成員函式:有一個隱形的“this”指標 void f1()//A* this { this->b; f2(); } //靜態成員函式// 靜態成員函式沒有“this”指標 //不能訪問成員變數以及成員函式,只能訪問靜態的成員變數和靜態的成員函式 static void f2() { //f1(); a; } }; int A::a = 0; void main() { A::f2(); A a; a.f2(); //函式指標不能指向類的成員函式 //void (*p)() = a.f1; //函式指標可以指向類的靜態成員函式 void (*p)() = A::f2; system("pause"); } class STU { char name[32]; int id; int age; }; void test() { STU stu[5]; //按照姓名進行排序 STU::sort(stu,5,STU::sortByName); for (int i = 0;i < 5; ++i) std::cout<<stu[i].name<<stu[i].id<<stu[i].age<<"\n"; //按照年齡進行排序 STU::sort(stu,5,STU::sortByAge); //按照ID進行排序 STU::sort(stu,5,STU::sortByID); }
---------//正解
#include <iostream> class STU {public: char name[32]; int id; int age; static void sort(STU* arr, int len, bool (*bj)(STU&,STU&) ) { for (int i = len-1; i > 0; --i) { for (int j = 0;j < i; ++j) { if ((*bj)(arr[j] , arr[j+1])) { STU temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } static bool sortByName(STU& a,STU& b) { return strcmp(a.name,b.name) == 1; } static bool sortByID(STU& a,STU& b) { return a.id > b.id; } static bool sortByAge(STU& a,STU& b) { return a.age > b.age; } }; void main() { STU stu[5]; strcpy(stu[0].name,"abc"); stu[0].id = 1; stu[0].age = 40; strcpy(stu[1].name,"def"); stu[1].id = 2; stu[1].age = 54; strcpy(stu[2].name,"你好"); stu[2].id = 4; stu[2].age = 2; strcpy(stu[3].name,"123456"); stu[3].id = 4; stu[3].age = 65; strcpy(stu[4].name,"87wef"); stu[4].id = 876; stu[4].age = 34; //STU::sort(stu, 5, STU::sortByName); //STU::sort(stu, 5, STU::sortByID); STU::sort(stu, 5, STU::sortByAge); for (int i = 0; i < 5; ++i) { std::cout<<stu[i].name<<", " <<stu[i].id<<", " <<stu[i].age<<std::endl; } system("pause"); }