在C++语法中,派生类中的构造函数操作是一个重要知识点,构造函数是用来初始化对象的。
基类构造函数总是先于派生类构造函数被调用。因为基类是派生类的基础,所以必须先创建基类。如果不指定要使用的基类构造函数,编译器就安排调用默认的基类构造函数。
规则:创建对象时首先调用基类的构造函数,然后调用派生类的构造函数;而销毁对象时首先调用派生类的析构函数,然后调用基类的析构函数。
#pragma once
#include <iostream>
#include <iomanip>
using namespace std;
//基类
class Box
{
public:
Box()
{
cout << "不带参数的父类构造函数\n";
}
Box(double lv, double wv, double hv) : length{ lv }, width{ wv }, height{ hv } //显式调用父类的构造函数
{
cout << "带三个参数的父类构造函数\n";
}
Box(double side) : Box{ side, side, side }
{
cout << "带一个参数的父类构造函数\n";
}
~Box()
{
}
double getLength()
{
return length;
}
double getWidth()
{
return width;
}
double getHeight()
{
return height;
}
double volumn() const
{
return length * width * height;
}
friend ostream& operator<<(ostream& stream, const Box& box);
protected:
double length{ 1.0 };
double width{ 1.0 };
double height{ 1.0 };
private:
};
inline ostream& operator<<(ostream& stream, const Box& box)
{
stream << "Box(" << setw(2) << box.length << ","
<< setw(2) << box.width << ","
<< setw(2) << box.height << ")";
}
#pragma once
#include "Box.h"
//派生类
class Carton : public Box
{
public:
Carton(double lv, double wv, double hv, const string desc) : Box{ lv, wv, hv }, material{ desc }
{
cout << "带四个参数的子类构造函数\n";
}
Carton(const string desc) : material{ desc }
{
cout << "带一个参数的子类构造函数\n";
}
Carton(double side, const string desc) : Box{ side }, material{ desc }
{
cout << "带两个参数的子类构造函数\n";
}
Carton()
{
cout << "不带参数的子类构造函数\n";
}
private:
string material{ "纸盒" };
};#include "Carton.h"
int main()
{
Carton carton1;
cout << "---------------------\n";
Carton carton2{ "One" };
cout << "---------------------\n";
Carton carton3{ 4.0, 5.0, 6.0, "Four" };
cout << "---------------------\n";
Carton carton4{ 2.0, "Two" };
cout << "---------------------\n";
cout << "carton1 volumn is " << carton1.volumn() << endl;
cout << "carton2 volumn is " << carton2.volumn() << endl;
cout << "carton3 volumn is " << carton3.volumn() << endl;
cout << "carton4 volumn is " << carton4.volumn() << endl;
getchar();
return 0;
} 
版权声明:本文为qq_37769473原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。