例5-1单继承
#include<iostream>
using namespace std;
class Base
{
private:
int b1;
protected:
int b2;
public:
void set(int m, int n)
{
b1 = m;
b2 = n;
}
void show()
{
cout << "b1=" << b1 << endl;
cout << "b2=" << b2 << endl;
}
};
class Derived :public Base
{
private:
int d;
public:
void setall(int m, int n, int l)
{
set(m, n);
d = l;
}
void showall()
{
show();
cout << "d=" << d << endl;
}
};
int main()
{
Derived obj;
obj.setall(30, 40, 50);
obj.show();
obj.showall();
return 0;
}
构造函数与析构函数的调用次序
#include<iostream>
using namespace std;
class Member
{
public:
Member()
{
cout << "constructing Member\n";
}
~Member()
{
cout << "destructing Member\n";
}
};
class Base
{
public:
Base()
{
cout << "constructing Base\n";
}
~Base()
{
cout << "destructing Base\n";
}
};
class Derived :public Base
{
private:
Member mem;
public:
Derived()
{
cout << "constructing Derived\n";
}
~Derived()
{
cout << "destructing Derived\n";
}
};
int main()
{
Derived obj;
return 0;
}
基类带参构造函数调用示例
#include<iostream>
using namespace std;
class Base
{
private:
int x;
public:
Base(int i)
{
x = i;
cout << "constructing Base\n";
}
void show()
{
cout << "x=" << x << endl;
}
};
class Derived :public Base
{
private:
Base d;
public:
Derived(int i) :Base(i), d(i)
{
cout << "constructing Deriverd\n";
}
};
int main()
{
Derived obj(100);
obj.show();
return 0;
}
|