【问题标题】:Returning static variable throws error in Visual studio [duplicate]返回静态变量在 Visual Studio 中引发错误 [重复]
【发布时间】:2020-11-04 06:40:22
【问题描述】:

在静态函数中返回或访问静态变量会在 Visual Studio 中引发错误:

// H File
class LayoutManager : public QObject
{
    static int Access_Data();
    static int data;
};
// CPP

static int data= 0; // Global scope

int LayoutManager::Access_Data()
{
    data= data+ 1;
    return data;
}
Error: Error    LNK2001 unresolved external symbol "public: static int LayoutManager::data" (?mm@LayoutManager@@2HA)

在C++中改成int LayoutManager::data = 0后,错误消失了,但是在另一个类中给data赋值时,又抛出了一个新的错误:

void MyLayout::Update( void )
{
    LayoutManager::data = 1;  // error here

【问题讨论】:

  • 请不要在您的问题中编辑答案,如果答案没有解决您的问题,请在答案中添加评论。如果您有新问题,请提出新问题

标签: c++ visual-c++ static c++14


【解决方案1】:

试试这个

int LayoutManager::data = 0;

这告诉编译器您的意思是 LayoutManager 类中的 data 变量,而不是任何类之外的常规全局变量。

重复static关键字也是错误的。编译器已经从声明中知道变量是静态的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多