#include<iostream> using namespace std; class Date { public: int day,month,year; void init(int,int,int); void print_ymd(); }; void Date::init(int yy, int mm, int dd) { year = yy; month = mm; day = dd; } void Date::print_ymd() { std::cout << year << "-" << month << "-" << day << std::endl; } int main() { Date date1; Date *p1 = &date1; //指向对象的指针 p1->init(2006, 3, 28); p1->print_ymd(); int *p2; p2 = &date1.year; //指向对象数据成员的指针 std::cout << *p2 << std::endl; void (Date:: * p3)(int,int,int); //指向对象成员函数的指针 void (Date:: * p4)(); //指向对象成员函数的指针 p3 = Date::init; p4 = Date::print_ymd; (date1.*p3)(2006, 4, 8); (date1.*p4)(); return 0; }
编译的时候会报错:
35:13: error: invalid use of non-static member function ‘void Date::init(int, int, int)’
p3 = Date::init;
36:13: error: invalid use of non-static member function ‘void Date::print_ymd()’
p4 = Date::print_ymd;
将p3= Date::init;改为:
p3 = &Date::init;
将p4 = Date::init;改为:
p4 = &Date::print_ymd;
C++的非静态成员函数在未实例化之前地址是不确定的,所以要将Date的两个成员函数
的地址指明之后才能进行赋值操作。
时间: 2024-10-11 03:38:49