#include <iostream>
using namespace std;
/**********************c++类的学习******************************************/
//封装性
//数据和方法放在定义一起
//一般不能直接访问->访问限定符 限制了类外访问
class Stack
{
//1.成员函数
//2.成员变量
public:
void push(int x);//1.在类里面定义 2.类里声明,类外定义
void pop();
bool empty();
private:
int * _a;
int _size;
int _capacity;
};
//c语言中struct 用来定义结构体
//2.c++中。兼容c的struct定义结构体的用法、但是struct中也可以定义类
//class默认私有 struct 默认公有
//c
struct ListNode1{
int _va;
};
//c++
struct ListNode2{
int val;//声明
ListNode2* createnode(int val);//成员函数
};
/****************************************************************/
/****************************类的实例化************************************/
/*
*声明与定义的区别?
* 1.声明可以是一种承偌但是还没有做。定义就是已经做了
*/
void Stack ::pop(){
}
void test01()
{
//类实例化对象,相当于定义出了类的成员变量的空间,开辟出了空间
Stack s1;
Stack s2;
//s1.push(1);
//对象中,只存储成本变量,不储存成员函数
cout<<sizeof (s1)<<endl;
//一个类实例化出N个对象,每个对象的成员变量都可存储不同的值,但调研=用函数是同一个
//如果每个对象都放成员函数。而这些成员函数的都是一样的。浪费空间
}
/****************************************************************/
/**********************构造函数******************************************/
/**
this 存在在栈上
函数在公共代码段
变量在程序段上
* @brief The Date class
*/
class Date
{
private:
int _year;
int _month;
int _day;
public:
/**构造函数,在函数初始时使用
* 1.没有返回值
* 2.自动调用
* 3.可以重载
* 4.
* 5.如果没有显示定义构造函数,构造器会默认构建一个无参的构造函数
* 1.针对内置类型没有出理好
* 2.针对自定义类型的成员变量,
* 一旦显示定义。就会调用带参的
* @brief Date
*/
Date(int year,int month,int day){
_year=year;
_month=month;
_day=day;
}
Date()
{
}
void getString()
{
cout<<_year<<" "<<_month<<" "<<_day<<endl;
}
void init(int year,int month,int day)
{
this->_year=year;
this->_month=month;
this->_day=day;
}
};
void test02()
{
Date d1;//1.默认调用自己实现的无参构造函数2、全缺省的构造函数也被看成无参3.编译器自己生成的 3个只容得下一个
d1.getString();
d1.init(1,1,1);
d1.getString();
return;
}
/**
***寄存器 cache(l1,l2,l3) 主存() 外存
***
***
*/
/****************************************************************/
/*******************************类与对象*********************************/
class time{
};
void test03()
{
Date d1;
d1.getString();
Date *d2 = new Date(1,5,1);
d2->getString();
Date d3(1,1,1);
d3.getString();
}
/****************************************************************/
int main()
{
test03();
return 0;
}
c++学习第三天
最新推荐文章于 2024-07-24 20:55:30 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)