#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
//C语言中,结构体中只能定义变量,在C++中,结构体内不仅可以定义变量,也可以定义函数。
#if 0
#include<stdlib.h>
struct Student
{
void SetStudentInfo(const char* name, const char* gender, int age)
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
}
void PrintStudentInfo()
{
cout << _name << " " << _gender << " " << _age << endl;
}
char _name[20];
char _gender[3];
int _age;
};
int main()
{
Student s;
s.SetStudentInfo("lc", "男", 18);
s.PrintStudentInfo();
system("pause");
return 0;
}
#endif
//1. public修饰的成员在类外可以直接被访问
//2. protected和private修饰的成员在类外不能直接被访问(此处protected和private是类似的)
//3. 访问权限作用域从该访问限定符出现的位置开始直到下一个访问限定符出现时为止
//4. class的默认访问权限为private,struct为public(因为struct要兼容C)
#if 0
//结构体内存对齐规则
//1. 第一个成员在与结构体偏移量为0的地址处。
//2. 其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处。
// 注意:对齐数 = 编译器默认的一个对齐数 与 该成员大小的较小值。 VS中默认的对齐数为8,gcc中的对齐数为4
//3. 结构体总大小为:最大对齐数(所有变量类型最大者与默认对齐参数取最小)的整数倍。
//4. 如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最大对齐数的整数倍处,结构体的整体大小就是 所有最大对齐数(含嵌套结构体的对齐数)的整数倍。
class A
{
public:
void PrintA()
{
cout << _a << endl;
}
private:
char _a;
char _s;
int _b;
};
class B
{
};
int main()
{
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
system("pause");
return 0;
}
#endif
class Date
{
public:
void SetDate(int year, int mouth, int day)
{
_year = year;
_mouth = mouth;
_day = day;
}
void ShowDate()
{
cout << _year << "-" << _mouth << "-" << _day << endl;
}
private:
int _year;
int _mouth;
int _day;
};
class A
{
public:
void PrintA()
{
cout << _a << endl; //程序在此奔溃, 因为this指针为空
}
void Show()
{
cout << "Show()" << endl;
}
private:
int _a;
};
int main()
{
//Date d1, d2;
//d1.SetDate(2019, 4, 19);
//d2.SetDate(2019, 6, 19);
//d1.ShowDate();
//d2.ShowDate();
A* p = NULL;
p->PrintA();
p->Show();
system("pause");
return 0;
}
//this指针的特性
//1. this指针的类型:类型 const
//2. 只能在“成员函数”的内部使用
//3. this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this 形参。所以对象中不存储this指针。
//4. this指针是成员函数第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,不需要用户 传递
//5. this指针不能为空
C++类和对象(上)
于 2019-04-19 20:20:24 首次发布