栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

类和对象1

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

类和对象1

类、class

c++兼容c

  • C语言面向过程 – 数据和方法是分离的
  • CPP面向对象 – 数据和方法是封装在一起的
  • struct可以定义类但C++当中经常用class来定义类
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("Peter", "男", 18);//调用方法
	s.PrintStudentInfo();//调用方法
	return 0;
}
namespace bitc//命名空间
{
	struct Stack
	{
		int* a;
		int top;
		int capacity;
	};
	void StackInit(struct Stack* ps){}
	void StackPush(struct Stack* ps, int x){}
	// ...
}
// CPP
namespace bitcpp
{
	struct Stack
	{
	public:
		void Init(){}
		void Push(int x){}
		void Pop(){}
		void Destory(){};
	private://改成public就可以运行了,因为private是私有的,不能在main访问
		int* a;
		int top;
		int capacity;
	};
}
int main()
{
	struct bitc::Stack stc;
	bitc::StackInit(&stc);
	bitc::StackPush(&stc, 1);
	bitc::StackPush(&stc, 2);

	bitcpp::Stack stcpp;
	stcpp.Init();
	stcpp.Push(1);
	stcpp.Push(2);
	//stcpp.top = 0;
	return 0;
}

类和对象

类的大小


结构体内存对齐

this
class Date
{
public:
	void Display()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
		//cout << this->_year << "-" << this->_month << "-" << this->_day << endl;---可以这样写
	}
	// void Init(Date* this, int year, int month, int day) ---不能这样写,这是编译器干的
	void Init(int year, int month, int day)
	{
		// 成员函数里面。我们不加的话,默认会在成员前面this->
		// 我们也可以显示的在成员前面this->
		_year = year;
		_month = month;
		_day = day;
		// 对象可以调用成员函数,成员函数中还可以调用成员函数
		// 因为有this指针
		//this->Display();
	}
private:
	int _year; // 年
	int _month; // 月
	int _day; // 日
};
int main()
{
	Date d1;
	Date d2; 
	d1.Init(2021, 10, 8); // d1.Init(&d1, 2021, 10, 8);
	d2.Init(2022, 10, 8); // d2.Init(&d2, 2021, 10, 8);
	d1.Display(); // d1.Display(&d1);
	d2.Display(); // d2.Display(&d2);
	return 0;
}



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/317128.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号