1、类其实也是一种作用域
#include<iostream>
using namespace std;
class A{
public:
typedef int INT;
static void show();
void work();
};
void A::show(){ cout<<"show()"<<endl; }
void A::work(){ cout<<"work()"<<endl; }
int main(){
A a;
a.work(); //通过对象访问普通成员
a.show(); //通过对象访问静态成员
A::show(); //通过类访问静态成员
A::INT n = 10; //通过类访问 typedef 定义的类型
return 0;
}
迭代器iterator应该是容器Vector的typedef类型
静态成员既可以通过对象访问,又可以通过类访问,而 typedef 定义的类型只能通过类来访问
2、结构体是否有构造函数和析构函数,C里面没有,C++里面有。
C++里根本就没有结构,仅仅为了兼容c才有结构这种东西,实际上除了名字以外,C++的结构就是类!!
3、vector其实是C++中的一个“类模板”
类模板中的成员函数并不是一开始就创建的,在调用时才去创建。
4、如果既不写 private 也不写 public,就默认为 private。
构造函数必须是 public 属性的
模板类创建对象时调用的是模板的构造函数,如下代码,Compare创建的对象是Compare类的构造函数,而不是Student类的构造函数:
#include <iostream>
using namespace std;
class Student
{
string name;
int age;
public:
Student() { cout << "default construct1" << endl; }
};
typedef struct {
int a;
int b;
} st;
template <class T> //声明一个模板,虚拟类型名为T。注意:这里没有分号。
class Compare //类模板名为Compare
{
public:
Compare() { cout << "default construct2" << endl; }
Say(T a)
{
cout << sizeof(a) << endl;
}
};
int main()
{
Student ik;
Compare<Student> StudentObj;
StudentObj.Say(ik);
}
编译和输出:
PS D:\gcc_gdb\cpp2\vector> g++ .\templateClass.cpp -o templateClass
PS D:\gcc_gdb\cpp2\vector> .\templateClass.exe
default construct1
default construct2
28
其实在 C++ 中,数组也是容器。数组的迭代器就是指针,而且是随机访问迭代器。例如,对于数组 int a[10],int * 类型的指针就是其迭代器。则 a、a+1、a+2 都是 a 的迭代器。
vector 容器在进行扩容后,与其相关的指针、引用以及迭代器可能会失效