目录
前言
auto关键字(c++11)
基于范围的for循环(c++11)
void testfor()
{
int array[] = { 1, 2, 3, 4, 5 }; for(auto& e : array)
e *= 2;
for(auto e : array)
cout << e << " ";
return 0;
}
范围for的使用
void testfor(int array[])
{
for(auto& e : array)
cout<< e <<endl;
}
指针空值nullptr(c++11)
面向过程和面向对象认识
类的引入
typedef int datatype;
struct stack
{
void init(size_t capacity)
{
_array = (datatype*)malloc(sizeof(datatype) * capacity); if (nullptr == _array)
{
perror("malloc申请空间失败"); return;
}
_capacity = capacity;
_size = 0;
}
void push(const datatype& data)
{
// 扩容
_array[_size] = data;
++_size;
}
datatype top()
{
return _array[_size - 1];
}
void destroy()
{
if (_array)
{
free(_array);
_array = nullptr;
_capacity = 0;
_size = 0;
}
}
datatype* _array;
size_t _capacity;
size_t _size;
};
int main()
{
stack s;
s.init(10);
s.push(1);
s.push(2);
s.push(3);
cout << s.top() << endl;
s.destroy();
return 0;
}
c语言结构体的定义,可以改成class,去试试吧!
类的定义
class classname
{
// 类体:由成员函数和成员变量组成
}; // 一定要注意后面的分号
// 我们看看这个函数,是不是很僵硬?
class date
{
public:
void init(int year)
{
// 这里的year到底是成员变量,还是函数形参?
year = year;
}
private:
int year;
};
// 所以一般都建议这样
class date
{
public:
void init(int year)
{
_year = year;
}
private:
int _year;
};
// 或者这样
class date
{
public:
void init(int year)
{
myear = year;
}
private:
int myear;
};
类的访问限定符
封装
类的作用域
class person
{
public:
void printpersoninfo();
private:
char _name[20]; char _gender[3]; int _age;
};
// 这里需要指定printpersoninfo是属于person这个类域
void person::printpersoninfo()
{
cout << _name << " "<< _gender << " " << _age << endl;
}
发表评论