用代码举例基类构造函数、对象成员构造函数、派生类本身的构造函数
时间: 2023-06-06 20:07:34 浏览: 58
基类构造函数的例子:
```
class Animal {
public:
Animal() {
cout << "Animal Constructor" << endl;
}
};
```
对象成员构造函数的例子:
```
class Teacher {
public:
Teacher(string name) : name(name) {
cout << "Teacher Constructor" << endl;
}
private:
string name;
};
class Student {
public:
Student() : teacher("Mr. Smith") {
cout << "Student Constructor" << endl;
}
private:
Teacher teacher;
};
```
派生类本身的构造函数的例子:
```
class Shape {
public:
Shape() {}
virtual int area() = 0;
};
class Rectangle : public Shape {
public:
Rectangle(int width, int height) : width(width), height(height) {}
int area() {
return width * height;
}
private:
int width;
int height;
};
```