在一个类中重载另一个类的构造函数

构造函数是一个特殊的操作符

假如我们有两个类point 和 Cpoint

现在我们需要用类point去构造Cpoint对象,一般实现方式是在Cpoint中定义如下构造:

Cpoint(point);

但有些情况下,这个构造是无法定义的:

  1. 用point的私有成员给Cpoint赋值(可以添加get方法解决),point没有定义Cpoint为友元类;
  2. 没有权限修改Cpoint,只能修改point;

这里我们可以在point重载Cpoint的构造函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
class Cpoint {
public:
Cpoint(int a) {
_p = a;
}
private:
int _p;
};
*/
class point {
public:
operator Cpoint() {
return Cpoint(_c_point);
}

private:
int _c_point;
};

重载后,在需要point构造Cpoint时都会隐式的调用point中的重载构造函数

1
2
3
point p1;
std::vector<Cpoint> vec;
vec.push_back(p1);//这个过程就是 由p1隐式构造Cpoint对象存入vec

完整测试源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <string>
#include <vector>

class Cpoint {
public:
Cpoint() {
std::cout << "Cpoint:" << std::endl;
_p = 0;
}
Cpoint(int a) {
std::cout << "Cpoint_a:" << a << std::endl;
_p = a;
}
private:
int _p;
};

class point {
public:
point() {
_c_point = 1;
std::cout << "point::point:" << _c_point << std::endl;
}
operator Cpoint() {
_c_point = 3;
std::cout << "point::Cpoint:" << _c_point << std::endl;
return _c_point; //等价于 Cpoint(_c_point)
}
private:
int _c_point;
};

int main(){
point p;
Cpoint cp(p);

point p1;
std::vector<Cpoint> vec;
vec.push_back(p1);

system("pause");
return 0;
}
/*
output:
point::point:1
point::Cpoint:3
Cpoint_a:3
point::point:1
point::Cpoint:3
Cpoint_a:3
*/

本文标题:在一个类中重载另一个类的构造函数

文章作者:Tokey

发布时间:2020年05月12日 - 10:05

最后更新:2021年06月29日 - 22:06

原始链接:http://TokeyRoad.github.io/2020/05/12/在一个类中重载另一个类的构造函数/

许可协议: 转载请保留原文链接及作者。

0%