【问题标题】:Using static results in an undefined reference in this piece of code [duplicate]在这段代码中使用静态会导致未定义的引用[重复]
【发布时间】:2022-01-07 19:46:45
【问题描述】:

这是我面临的问题的 MSVP。 m_eventQueue 在下面的代码中是静态的有什么问题? 当它不是静态的时,它编译得很好。我希望它是静态的,因为我也计划在另一个类中使用它,并且它是它们之间的公共队列。

这是我得到的错误

badri@badri-All-Series:~/progs$ g++ --std=c++11 inher3.cpp 
/tmp/ccGTVi2d.o: In function `RecordingConfigJobStateSignal::RecordingConfigJobStateSignal(std::shared_ptr<EventQueue> const&)':
inher3.cpp:(.text+0x13c): undefined reference to `commonQueue::m_eventQueue'
collect2: error: ld returned 1 exit status

这是inher3.hpp

#include<iostream>
#include<memory>
#include<queue>
using namespace std;
class EventBase
{
public:

private:
        int a;
};
using EventBasePtr = std::shared_ptr<EventBase>;

class SubscriptionManager
{

        public:
                int x;
};

class EventQueue
{
public:
    explicit EventQueue( SubscriptionManager& ){};
    ~EventQueue();
private:
    std::queue< EventBasePtr >          m_queue;
};
using EventQueuePtr = std::shared_ptr<EventQueue>;


class commonQueue
{
        public:             
                int *a;
                static std::queue< EventBasePtr >       m_queue;
                static EventQueuePtr m_eventQueue;
};

class RecordingConfigJobStateSignal: public commonQueue
{
        public:
                int c;
                RecordingConfigJobStateSignal( const EventQueuePtr &);
        private:
                int b;

};

这是inher3.cpp

#include<iostream>
#include"inher3.hpp"

RecordingConfigJobStateSignal::RecordingConfigJobStateSignal( const EventQueuePtr& eventQueue )//:m_eventQueue( eventQueue )
{
        /* m_eventQueue is actually from class commonQueue */
        m_eventQueue = eventQueue;
}

int main()
{
        return 0;
}


【问题讨论】:

  • 您只需声明 commonQueue 类中的静态成员变量。您还需要定义它们。 A decent book,教程或课程应该有你需要的信息。

标签: c++


【解决方案1】:

当您在类中声明静态成员时,C++ 要求您在类外部显式定义该成员。将此放在您的班级之外的 .cpp 文件中:

/*static*/
EventQueuePtr commonQueue::m_eventQueue;

【讨论】:

  • 还有一点,你可以把静态成员当作一个全局变量,前面加“commonQueue::”。更具体地说,当您将代码链接为库时,您需要像全局变量一样链接它,它需要作为符号导出。
猜你喜欢
  • 1970-01-01
  • 2011-04-09
  • 2016-07-30
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
相关资源
最近更新 更多