#include<iostream>usingnamespacestd;
class Basea {
public:
Basea() {
cout << "it is Basea" << endl;
}
virtual ~Basea() {
cout << "destruction of Basea" << endl;
}
// s声明为虚函数的时候才能够在delete的时候将两个对象的内存全部释放,否则派生类的内存没有// 释放,进而导致内存垃圾
};
class derived:public Basea {
public:
derived() {
cout << "it is derived" << endl;
}
~derived() {
cout << "destruction of derived" << endl;
}
};
int main() {
Basea* p = new derived;
delete p;
return0;
}
2.default function
#include<iostream>usingnamespacestd;
// 此处n个参数没有默认值就要求输入的时候至少要有>= n个实参void func(int a = 0, int b, int c = 0) {
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
int main() {
func(1);
return0;
}
// 可以是void func(int a, int b = 0, int c = 0)// 但是不可以是void func(int a = 1, int b, int c = 2);// 因为但只传入一个参数的时候,默认是第一个,而此时第二个参数却没有默认值,就会出现错误,// complie error:// test.cpp:5:6: error: default argument missing for parameter 2 of ‘void func(int, int, int)// void func(int a = 0, int b, int c = 0) {
3.static member function
#include<iostream>usingnamespacestd;
class test {
private:
staticint count;
int num;
public:
test(int a) {
count++;
num = a;
}
staticint getCount();
};
// 后面加上const会报错,尚未理解原因// static int getCount() const; 不可以// compile:// static.cpp:17:22: error: static member function ‘static int test::getCount()’// declared with type qualifiers// int test::getCount() const {int test::count = 0;
int test::getCount(){
return count;
}
int main() {
cout << test::getCount() << endl; // 注意因为静态成员函数属于类,但并不是单个对象的独有函数// 注意这两种调用方式
test t = test(1);
cout << t.getCount() << endl;
return0;
}
4.inheritance
#include<iostream>usingnamespacestd;
class A {
public:
A() {
cout << "A" << endl;
}
~A() {
cout << "~A" << endl;
}
};
class B {
public:
B() {
cout << "B" << endl;
}
~B() {
cout << "~B" << endl;
}
};
class C : public B, public A {
public:
C() {
cout << "C" << endl;
}
~C() {
cout << "~C" << endl;
}
};
int main() {
C c;
return0;
}
// B// A// C// ~C// ~A// ~B
5.inheritance again
// 派生类可以继承基类的静态成员函数和静态数据成员,不可以继承基类的友元函数// 派生类可以访问基类的ptotected成员#include<iostream>using namespace std;
class BASE {
public:
BASE();
void get_ij();
staticvoidget() {
cout << count << endl;
}
protected:
int i, j;
staticint count;
private:
int x_temp;
};
int BASE::count = 0;
class Y:public BASE {
public:
Y() {
count++;
}
void increment();
private:
float nmember;
};
BASE::BASE() {
count++;
i = j = x_temp = 0;
}
void BASE::get_ij() {
cout << i << ' ' << j << endl;
}
void Y::increment() {
i++;
j++;
}
int main() {
BASE obj1;
obj1.get();
Y obj2;
obj2.increment();
obj2.get_ij();
obj1.get();
obj2.get();
obj1.get_ij();
}
// output:// 1// 1 1// 3// 3// 0 0// 因为友元函数不属于类的成员函数,所以很明显的,派生类不能够继承类的友元函数// error: ‘class Y’ has no member named ‘get_ij’// obj2.get_ij();