构造函数
例 4_1 修改版 1
//类定义
class Clock {
public:
Clock(int newH,int newM,int newS);//构造函数
void setTime(int newH, int newM, int newS);
void showTime();
private:
int hour, minute, second;//私有数据成员
};
//构造函数的实现://初始化列表
Clock::Clock(int newH, int newM, int newS) : hour(newH),minute(newM),
second(newS) {
}
//其它函数实现同例4_1
int main() {
Clock c(0,0,0); //自动调用构造函数
c.showTime();
return 0;
}
例 4_1 修改版 2
class Clock {
public:
Clock(int newH, int newM, int newS); //构造函数
Clock(); //默认构造函数
void setTime(int newH, int newM, int newS);
void showTime();
private:
int hour, minute, second;
};
Clock::Clock(): hour(0),minute(0),second(0){ }//默认构造函数,:为初始化列表
Clock::Clock(int newH, int newM, int newS) : hour(newH),minute(newM),
second(newS) { //构造函数
}
//其它函数实现同前
int main() {
Clock c1(0, 0, 0); //调用有参数的构造函数
Clock c2; //调用无参数的构造函数
……
}
委托构造函数还是有点疑问

使用引用去读取它里面的数据,但是不能用引用来修改对象。
复制构造函数定义
复制构造函数是一种特殊的构造函数,其形参为本类的对象引用。作用是用一个已
存在的对象去初始化同类型的新对象。
class 类名 {
public :
类名(形参);//构造函数
类名(const 类名 &对象名);//复制构造函数
// …
};
类名::类( const 类名 &对象名)//复制构造函数的实现
{ 函数体 }
复制构造函数的例子
#include <iostream>
using namespace std;
//类的定义
class Point { //Point 类的定义
public:
Point(int xx=0, int yy=0) { x = xx; y = yy; } //构造函数,内联
Point(const Point& p); //复制构造函数
void setX(int xx) {x=xx;}
void setY(int yy) {y=yy;}
int getX() const { return x; } //常函数(第5章)
int getY() const { return y; } //常函数(第5章)
private:
int x, y; //私有数据
};
//复制构造函数的实现
Point::Point (const Point& p) {
x = p.x;
y = p.y;
cout << "Calling the copy constructor " << endl;
}
//形参为Point类对象
void fun1(Point p) {
cout << p.getX() << endl;
}
//返回值为Point类对象
Point fun2() {
Point a(1, 2);
return a;
}
int main() {
Point a(4, 5);
a.setX(7);
a.setY(8);
cout << a.getX() << endl;
Point b(a); //用a初始化b。
cout << b.getX() << endl;
fun1(b); //对象b作为fun1的实参
b = fun2(); //函数的返回值是类对象
cout << b.getX() << endl;
return 0;
}
单步调试熟悉复制构造函数
#include <iostream>
using namespace std;
class MyClass{
private:
int num;
public:
MyClass(int d):num(d){
}
MyClass(const MyClass& original):num (original.num){
cout << "123123"<< endl;
}
friend void print(MyClass C){
cout<<C.num;
}
};
int main(){
MyClass c(5);
MyClass *p1;
p1=&c;
print(*p1);
print(c);
return 0;
}
本文介绍了C++中的构造函数,包括如何定义和使用构造函数来初始化类的对象。同时,详细讲解了复制构造函数的概念和作用,通过示例展示了复制构造函数如何在对象复制过程中确保数据的一致性。此外,还提供了单步调试复制构造函数的实例,帮助理解其实现过程。
194

被折叠的 条评论
为什么被折叠?



