1、默认构造函数
#include <iostream>
using namespace std;
/* 定义Line类 */
class Line
{
public:
Line(){}; // 默认构造函数
void setLength( double len ); // 声明成员函数setLength
double getLength( void ); // 声明成员函数getLength
private:
double length;
};
/* 定义成员函数:设置长度 */
void Line::setLength( double len )
{
length = len;
}
/* 定义成员函数:获取长度 */
double Line::getLength( void )
{
return length;
}
/* 主函数 */
int main( )
{
Line line;
line.setLength(6.00);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
2、带参数构造函数
#include <iostream>
using namespace std;
// 定义一个类
class Person
{
private:
string name; // 姓名
int age; // 年龄
public:
// 带参数的构造函数
Person(string n, int a)
{
name = n; // 初始化姓名
age = a; // 初始化年龄
}
// 成员函数,用于显示信息
void display()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main()
{
// 创建Person对象时,通过构造函数传递参数
Person p1("Alice", 25);
p1.display(); // 输出:Name: Alice, Age: 25
Person p2("Bob", 30);
p2.display(); // 输出:Name: Bob, Age: 30
return 0;
}
3、复制构造函数
#include <iostream>
using namespace std;
// 定义一个类
class Person
{
private:
string name; // 姓名
int age; // 年龄
public:
// 普通构造函数
Person(string n, int a) : name(n), age(a) {}
// 复制构造函数
Person(const Person& other)
{
name = other.name; // 深拷贝姓名
age = other.age; // 深拷贝年龄
}
// 显示信息
void display()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main()
{
// 创建一个Person对象
Person p1("Alice", 25);
p1.display(); // 输出:Name: Alice, Age: 25
// 使用复制构造函数创建另一个对象
Person p2(p1);
p2.display(); // 输出:Name: Alice, Age: 25
return 0;
}
4、参数初始化列表
#include <iostream>
using namespace std;
// 定义一个类
class Person
{
private:
string name; // 姓名
int age; // 年龄
public:
// 普通构造函数
Person(string n, int a) : name(n), age(a) {}
// 复制构造函数
Person(const Person& other)
{
name = other.name; // 深拷贝姓名
age = other.age; // 深拷贝年龄
}
// 显示信息
void display()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main()
{
// 创建一个Person对象
Person p1("Alice", 25);
p1.display(); // 输出:Name: Alice, Age: 25
// 使用复制构造函数创建另一个对象
Person p2(p1);
p2.display(); // 输出:Name: Alice, Age: 25
return 0;
}
5、子类显示调用父类构造函数
#include <iostream>
#include <string.h>
using namespace std;
/* 定义父类 */
class CEmployee
{
public:
CEmployee()
{
cout <<"CEmployee的构造函数CEmployee()被调用"<<endl;
}
CEmployee(const char name[])
{
cout << "带参数构造函数CEmployee(char name[])被调用" << endl;
}
~CEmployee()
{
cout <<"CEmployee的析构函数~CEmployee()被调用"<<endl;
}
};
/* 子类Operator公有继承CEmployee */
class COperator : public CEmployee
{
public:
COperator()
{
cout <<"COperator的构造函数COperator()被调用"<<endl;
}
COperator(const char name[]):CEmployee(name)
{
cout << "带参数构造函数COperator(char name[])被调用" << endl;
}
~COperator()
{
cout <<"COperator的析构函数~COperator()被调用"<<endl;
}
};
/* 主程序 */
int main(int argc, char *argv[])
{
// COperator O1;
COperator O2("Linux");
return 0;
}
xuanmiao@linux:~/Test/C++$ ./test6
带参数构造函数CEmployee(char name[])被调用
带参数构造函数COperator(char name[])被调用
COperator的析构函数~COperator()被调用
CEmployee的析构函数~CEmployee()被调用
构造函数
浙公网安备 33010602011771号