Class的基本结构
下面描述的是一个简单的class,有一个变量value,一个类函数,一个构造函数,一个析构函数,其中构造函数和析构函数不是必须存在的。
class hello_world {
public:
int value; /* 成员 */
public:
void fun(int a, int b); /* 类函数 */
public:
hello_world(); /* 构造函数 */
~hello_world(); /* 析构函数 */
};
构造函数:一种特殊的成员函数,它会在每次创建类的新对象时执行。
析构函数:一种特殊的成员函数,它会在每次删除所创建的对象时执行。
一些情况下,可能在构建类的时候需要做一些初始化等等的额外操作,这个时候就需要实现构造函数。同理,需要释放一些资源的时候可以放在析构函数里面进行。如果不实现这两个函数,系统会默认创建,系统默认构建的函数是空实现。详见构造/析构函数的说明
实现构造/析构函数
hello_world::hello_world() {
std::cout << "hello world" << std::endl;
}
hello_world::~hello_world() {
std::cout << "goodbye world" << std::endl;
}
实现类函数
void hello_world::fun(int a, int b) {
int c = a + b;
std::cout << "c: " << c << std::endl;
}
使用Class
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
/* 方法1 */
hello_world hw1;
hw1.value = 1;
hw1.fun(1, 2);
/* 方法2 */
hello_world *hw2 = new hello_world();
hw2->value = 2;
hw2->fun(3, 4);
delete hw2;
return 0;
}
方法1:直接定义出来一个hello_world class,直接进行操作。
方法2:通过new的方式定义一个hello_world class。
它们的区别和适用场景如下:
- 方法1定义出来的class,不需要手动释放,在函数执行结束的时候会自动运行析构函数。方法2则是在调用delete的时候去执行析构函数,如果只new却没有delete,会造成内存泄露。
- 方法2使用的是堆空间,而方法1的方式,如果是局部的,则使用的栈空间。
数据初始化
有些类的成员变量需要在初始化的时候赋初始值,以防止出现未知的错误。
方法1:在构造函数里进行初始化
#include <iostream>
class hello_world {
public:
int value;
public:
hello_world();
~hello_world();
};
hello_world::hello_world() {
this->value = 5;
}
hello_world::~hello_world() {
}
int main(int argc, char const *argv[]) {
hello_world hw;
std::cout << "value: " << hw.value << std::endl;
return 0;
}
打印结果:value: 5
方法2:通过使用初始化列表进行成员的初始化
#include <iostream>
#include <string>
using namespace std;
class test {
public:
test() : value1(1), value2(2), value3(3) {}
public:
int value1;
int value2;
int value3;
};
int main(int argc, const char** argv) {
test t;
cout << t.value1 << endl; /* 输出:1 */
cout << t.value2 << endl; /* 输出:2 */
cout << t.value2 << endl; /* 输出:3 */
return 0;
}