【问题标题】:CLion: can't be resolve <member_variable_name>CLion:无法解析 <member_variable_name>
【发布时间】:2017-03-18 04:44:24
【问题描述】:

我有一个模板类 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

ServoLink.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 中有错误,我将不胜感激在识别它们方面的任何帮助。谢谢。

【问题讨论】:

  • 您忘记将ServoLink.h 包含在ServoLink.cpp 中。这就是为什么您会收到有关未知类型或 wharever 的错误。

标签: c++ templates cmake clion


【解决方案1】:

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

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

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

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

您还需要#include &lt;cstddef&gt; 以确保size_t 是已知类型。这说明sizesize_t 类型的模板参数,而您的原始代码试图定义其namesize_t 的模板参数。

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

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

inline 是可选的,但如果您将标头包含在多个 .cpp 文件中,则可能会使某些编译器对多个定义发出警告。有关这方面的更多信息,请参阅this answer。模板参数是 type size_t 并具有 name size。然后将模板参数 name 放在类名之后。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2017-11-13
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多