在构造函数中使用 class 成员时的 C++ 未定义引用

C++ Undefined reference when using class member in constructor

我是 C++ 的新手,所以这个问题听起来可能很愚蠢,但即使我用谷歌搜索了很长时间,我也找不到答案。我使用的是ROS环境,但是我的问题应该是一般的C++问题,所以我决定post这里

我有两个密码

1)

ros::Duration max_storage_time = ros::Duration().fromNSec(1ULL * 1000000000LL);
tf::TimeCache odometryCache(max_storage_time);

2)

tf::TimeCache odometryCache(ros::Duration max_storage_time = ros::Duration().fromNSec(1ULL * 1000000000LL));

第二个编译,而第一个不编译。对我来说,这似乎是完全一样的。第一个代码的错误是: 对 tf::TimeCache::TimeCache(ros::Duration)

的未定义引用

tf::TimeCache 的文档可以在 http://docs.ros.org/jade/api/tf/html/c++/classtf_1_1TimeCache.html#acca87a70aeb9c3573cdbfec26f6bfe23

找到

有人可以告诉我我缺少什么吗?代码片段之间的区别在哪里,为什么第一个不能编译?

提前致谢!

tf::TimeCache odometryCache(ros::Duration max_storage_time = ros::Duration().fromNSec(1ULL * 1000000000LL));

这是函数 odometryCache 的声明,而不是对 tf::TimeCache 的构造函数的调用。这在 C++ 中称为 "Most vexing parse"。

这里的正确修复很简单:

tf::TimeCache odometryCache(ros::Duration().fromNSec(1ULL * 1000000000LL))

或者,如果 C++11 可用:

tf::TimeCache odometryCache{ ros::Duration().fromNSec(1ULL * 1000000000LL) }

问题是您没有正确链接到 ROS 库。
解决方案是正确设置链接器。

只有第一个实际调用了任何 ROS 函数——第二个声明了一个接受 ros::Duration 和 returns 和 tf::TimeCache 的函数(这称为 "the most vexing parse") .

如果您从不尝试使用 odometryCache,第二个不会造成任何问题。
如果你这样做(例如,odometryCache.clearList()),编译器会抱怨你试图访问非聚合类型的成员,或者类似的东西。

如果您不尝试命名构造函数的参数:

tf::TimeCache odometryCache(ros::Duration().fromNSec(1ULL * 1000000000LL));

它会编译,但链接会像第一个片段一样失败。