gpt4 book ai didi

c++ - CLion:无法解析

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:15 24 4
gpt4 key购买 nike

我有一个模板类 ServoLink,它的头文件在“/include”中,源文件在“/src”中。 CMakeLists.txt 文件位于项目目录中,其中包含“include”和“src”文件夹。我开始在头文件中声明和定义所有函数,但我很快意识到我的错误,我正试图将函数定义转移到源文件中。但是,CLion 在源文件中告诉我该类的所有成员变量都无法解析。

以下是我的CMakeLists.txt:

cmake_minimum_required(VERSION 3.6)
project(Two_Link_Leg)

set(CCMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Werror -Wextra -pedantic -pedantic-errors")

include_directories("lib/Adafruit_PWMServoDriver")
include_directories(include)

set(SOURCE_FILES main.cpp src/ServoLink.cpp)
add_executable(Two_Link_Leg ${SOURCE_FILES})

ServoLink.h:

#ifndef TWO_LINK_LEG_SERVOLINK_H
#define TWO_LINK_LEG_SERVOLINK_H

#include <map>
#include "Adafruit_PWMServoDriver.h"

template <class size_t>
class ServoLink{

private:

//servo motor channel number on the PWM/Servo driver; [0, 15]
size_t mChannel;

//pointer to a map of the servo motor's angular position with its corresponding pulse width value
std::map<int, size_t>* mPWM;

//variable given by Adafruit
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

public:

ServoLink(size_t givenChannel, size_t givenPWM[]);
};

#include "../src/ServoLink.cpp"

#endif //TWO_LINK_LEG_SERVOLINK_H

伺服链接.cpp:

#include <stdexcept>
#include <map>

template<typename size_t size>
ServoLink<size_t>::ServoLink(size_t givenChannel, size_t givenPWM[]):mChannel(givenChannel){
mPWM= new std::map<int, size_t>;
for(size_t i= 0; i< size; i++){
mPWM->insert(std::make_pair(-90+((double)180*i/size), givenPWM[i]));
}
}

如果我的模板代码中有任何语法错误或 CMakeLists.txt 中有错误,我将不胜感激任何识别它们的帮助。谢谢。

最佳答案

您的代码中存在许多问题。第一,结构部分。无需将构造函数实现拆分为单独的 .cpp文件,如果需要,您也可以将其包含在标题中。如果您将构造函数的实现放在 header 中的类定义中,那就没问题了。如果将实现放在类定义之外,您可能希望将其标记为 inline ,但它仍然应该在没有它的情况下编译。

你不需要(事实上如果你这样做会得到一个错误)指定 .cpp文件作为提供给 add_executable() 的来源之一在您的 CMakeLists.txt 文件中。编译器将看到模板的内联实现并对此感到满意。在这种情况下无需显式尝试编译模板。

现在是代码错误。类定义的模板参数不正确。它们应该是:

template<size_t size>
class ServoLink {
...
};

您还需要#include <cstddef>确保size_t是已知类型。这说明的是 sizesize_t 类型的模板参数,而您的原始代码试图定义一个模板参数,其名称size_t .

如果你想在类定义之外定义构造函数实现,你需要这样做:

template<size_t size> inline
ServoLink<size>::ServoLink(size_t givenChannel, size_t givenPWM[]) ...

inline是可选的,但如果您将 header 包含在多个 .cpp 中,则可能会消除某些编译器关于多个定义的警告文件。参见 this answer有关这方面的更多信息。模板参数是类型 size_t并且有名字 size .然后,将模板参数 name 放在此处的类名之后。

通过这些更改(并组成一个微不足道的 main.cpp 以及注释掉对 Adafruit_PWMServoDriver header 和类的引用),代码为我编译。

关于c++ - CLion:无法解析 <member_variable_name>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com