类是虚的,类是观点,类是概念,类不是实体,对象是实体
local variable:
1: local variables are defined inside a method(函数), have a scope limited to
the method to which they belong
2: a local variable of the same name as a field(成员变量) will prevent
the field being accessed from within a method (在一个函数里本地变量会覆盖掉成员变量)
能够定义变量分三种:成员变量,本地变量,函数参数
1:所有的变量都能够存储对应类型的值
2:成员变量定义在构造函数和函数之外
3:成员变量在一个对象的生存期里市永远存在的
4:类的成员变量在类的成员函数里是可以直接调用的
5:定义类时定义的成员变量时一个declaratio不是definition,直到定义了对象才有definition
成员变量在每一个类的对象里面,类中只是声明了成员变量但是不拥有成员变量
6:参数和本地变量都是放在堆栈里面的
7:声明不会告诉你在哪里,只有定义才会说就在这里
函数是属于类的,不是属于对象的
this指针:this is a keyword. the hidden parameter (隐藏的参数)
this pointer to the caller // this 指向它的调用者
this is a hidden parameter for all member functions, with the type of class
void Point::print()
(can be regarded as -> ) void Point::print(Point *this)
编程中遇到 烫烫烫 是遇到没初始化的内存了
构造函数(constructor)
构造函数和类的名字是相同的而且没有任何返回类型。 A(){}
对象生成时自动调用构造函数
构造函数可以有参数,但是这样需要在定义对象时在对象后加上圆括号进行初始化
A::A(int i){x = i;} A a(1);
default constructor 是指没有参数的构造函数,编译器自动生成的构造函数叫 auto default constructor
析构函数(destructor)
析构函数没有参数和返回值,名字是在类名之前加 ~
~A(){}
对象消亡时自动调用析构函数, 是在空间被回收之前调用
不写,编译器默认生成
拷贝构造函数(复制构造函数)
其形参必须是引用,但并不限制为const,一般普遍的会加上const限制。
不写复制构造函数,编译器默认生成一个复制构造函数
A(const A &a){}
类型转换构造函数
讲一个其他类型转换成一个对象
例如 A(int i) { x = i; }
1、类型转换函数只能定义一个类的成员函数而不能定义为类的友元函数,类型转换类型也可以在类体中声明函数原型,而将函数体定义在类的外部
2、类型转换函数既没有参数,也不能在函数名前指定函数类型
3、类型函数中必须有return语句,必须送回目标类型的数据作为函数的返回值
存储空间是在进入大括号时就分配好了,但是构造函数要到运行对象被定义的那一行才会调用
一个对象没有被构造就不可以被析构
在c++ struct和class是一样的,但是有细微的差别
learning record code:
#include <iostream>
using namespace std;
class Point {
public:
Point(int i); // 构造函数
~Point(); // 析构函数
void init(int x, int y);
void print() const;
void move(int dx, int dy);
private:
int x, y;
};
Point::Point(int i)
{
x = y = i;
cout << "constructed" << endl;
}
Point::~Point()
{
cout << "destructed" << endl;
}
void Point::print() const
{
cout << x << " " << y << endl;
}
struct Y{
int x;
Y(int a) { x = a; }; // 构造函数可以重载
Y(){};
};
int main()
{
Point a(1);
Point b(2);
a.print();
b.print();
Y tm[2] = { Y(1) }; // tmp[1]用有参构造函数,tmp[2]用无参构造函数
return 0;
}