在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
new和delete用来申请动态内存空间,一定要配对使用 #include <string> #include <ctype.h> #include <vector> #include <iostream> #include <fstream> // using declarations states our intent to use these names from the namespace std using namespace std; int main() { int *p = static_cast<int*>(malloc(sizeof(int))); //对于内置类型,如int,double,float,char...即使不用new声明,使用delete释放也不会出任何编译,运行错误,但是对于任何类类型,不管是自定义还是系统自带的,都会出错误
成员地址,是相对于开始地址的相对偏移。 #include <string> #include <ctype.h> #include <vector> #include <iostream> #include <fstream> #include<new> // using declarations states our intent to use these names from the namespace std using namespace std; struct Date { int year; int month; int day; void print(){ cout << year << "-" << month << "-" << day << endl; } }; void showYear(Date a[], int length, int Date::*year); int main() { Date a[5] = { { 2001, 1, 1 }, { 2002, 2, 2 }, { 2003, 3, 3 }, { 2004, 4, 4 }, { 2005, 5, 5 } }; Date d = { 1997, 7, 9 }; cout << "&d = " << &d << endl; cout << "&d.year = " << &d.year << " &d.month = " << &d.month << " &d.day =" << &d.day << endl; //绝对地址 cout << &Date::year << &Date::month << &Date::day << endl;//成员地址打印出来是111,c++认为成员地址和函数地址无意义,所以都直接处理为true,在输出也就显示为1 //cout << static_cast<int*>(&Date::year) << endl; //那么,强转来看看地址,结果报错,不能转换 //匿名联合,两个变量同用同一个空间 union { int n; int Date::*mp; }; mp = &Date::day; cout << "n = " << n << endl;//输出8,相对于year的地址 //通过成员地址来访问结构中的成员 cout << d.*mp << endl; //应用,访问a数组中的,所有日期中的年份 showYear(a, sizeof(a)/sizeof(Date), &Date::year); //成员函数指针 d.print(); void (Date::*p)() = &Date::print; (d.*p)(); return 0; } void showYear(Date a[], int length, int Date::*p)//p是date中某个成员的地址,不可用day,year,month,会造成表达模糊 { for (int i = 0; i < length;++i) { cout << a[i].*p << " "; //a[i].year表达不出我想要用成员地址的意愿,因为year本来就是成员 //p是成员地址,*p是结构中的某个成员,a[i].*p,取出这个成员 } cout << endl; }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论