C++在构造函数中使用类成员时未定义的引用
我对C++很新,所以这个问题听起来很愚蠢,但即使我搜索了一段时间,但找不到答案。我使用ROS环境,但我的问题应该是一个普通的C++问题,所以我决定在这里发布它。C++在构造函数中使用类成员时未定义的引用
我有两个码
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
发现可能有人请告诉我,我缺少的是什么?代码段和第一个为什么不能编译的区别在哪里?
在此先感谢!
的问题是,你不正确的连接ROS库。
解决方案是正确设置链接器。
只有第一个实际调用任何ROS函数 - 第二个声明的函数需要ros::Duration
并返回tf::TimeCache
(这称为“最令人头痛的解析”)。
如果你永远不会尝试使用odometryCache
,第二个不会导致任何问题。
如果你这样做(例如,odometryCache.clearList()
),编译器会抱怨你试图访问非聚合类型的成员,或者沿着这些行。
如果你不尝试命名构造函数的参数:
tf::TimeCache odometryCache(ros::Duration().fromNSec(1ULL * 1000000000LL));
它将编译,但是链接会失败,就像第一个作品。
tf::TimeCache odometryCache(ros::Duration max_storage_time = ros::Duration().fromNSec(1ULL * 1000000000LL));
这是功能odometryCache
声明,不打电话的tf::TimeCache
构造。这在C++中被称为“最烦人的解析”。这里
正确的修复将是简单:
tf::TimeCache odometryCache(ros::Duration().fromNSec(1ULL * 1000000000LL))
,或者,如果可用C++ 11:
tf::TimeCache odometryCache{ ros::Duration().fromNSec(1ULL * 1000000000LL) }
对不起,但你的选项都没有编译,而我的代码的这个版本正在编译 – YeahScience
正如在另一个答案中所说,问题是在ROS的链接,所以你的答案也是正确的 – YeahScience
当你在'ros :: Duration max_storage_time = ros :: Duration()。from NSec(1ULL * 1000000000LL)''时,你在构造函数调用中做了什么?你有没有复制'ros :: Duration max_storage_time ='部分? – NathanOliver
是的,我相信,第二个(只使用一行)的作品。 – YeahScience