c++ - 转换指南

标签 c++ type-conversion

如果您有两个类 A 和 B,并且您需要定义从 A -> B 和 B -> A 的转换,那么标准解决方案是什么?

  1. 让 A 有一个构造函数接受 B 和 A 有转换运算符 到乙?
  2. 让 A 和 B 都拥有对方的构造函数?
  3. 让 A 和 B 都具有到另一个的转换运算符?
  4. 某种 CPO convert<To>(From)
  5. 还有其他办法吗???

(注2和注3需要循环依赖)

最佳答案

我在cppslack上问了一圈,好像没有标准/通用的情况,所以归结为这种情况。

(1) is what you do when you're extending an API, i.e. A knows about B but B doesn't know about A;

(2) or (3) is what you do when A and B are defined as part of the same API, i.e. they know about each other;

(4) is how you unify two unrelated APIs, i.e. neither A nor B knows about the other.

关于c++ - 转换指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58259002/

相关文章:

node.js - 将字符串转换为数字 node.js

Android Google Firebase 数据库对象值

c++ - 如何计算阿克曼函数调用自身的次数?

c++ - 虚拟方法会使应用程序变慢,但它们可以加快链接速度吗?

c++ - 在堆中定义不同大小的结构

java - 将 hibernate 数据类型映射到混合类型存储过程的输出

c++ - 这种情况下有什么样的多线程保护?

c++ - gluLookAt 似乎产生了错误的观点,OpenGL

ios - 如何在swift中将Data转换为Int

java - Double.parseDouble(String) 和 Double.valueOf(String) 有什么区别?