【问题标题】:Unable to access static member from static function无法从静态函数访问静态成员
【发布时间】:2021-08-29 02:11:19
【问题描述】:

我正在使用下面的代码 sn-p。

#include <iostream>
struct Entity
{
    static int x,y;
    
    static void print()
    {
        std::cout << x << " Yoo -- ooY " << y << std::endl;
    }
};
// int Entity::x;
// int Entity::y;
int main() {
    Entity::print();
    return 0;
}

我在尝试运行时遇到编译错误:

/usr/bin/ld: /home/ItfG3m/ccKGCJ5N.o: in function `main':
prog.cpp:(.text.startup+0xf): undefined reference to `Entity::x'
/usr/bin/ld: prog.cpp:(.text.startup+0x31): undefined reference to `Entity::y'
collect2: error: ld returned 1 exit status

如果我取消注释,它可以正常工作:

// int Entity::x;
// int Entity::y; 

静态方法不应该能够访问静态变量吗?为什么需要声明?

【问题讨论】:

  • 这不是访问问题(编译时);这是一个存在问题(链接时间)。您声明但从未定义您的静态成员xy。 IE。在你的课堂之外int Entity::x, Entity::y; 他们必须住在某处。请参阅有关 C++ 静态成员变量以及如何声明和定义它们的参考资料。任何基本文本都应包含所述信息,如果您的不包含,则不值得打印它的纸张。
  • @WhozCraig 感谢您的指出。如果由于某种原因我不能或不想在我的类/结构之外定义它。有没有办法做到这一点?
  • 有没有办法使用未定义的变量? 没有。

标签: c++ struct static


【解决方案1】:

您需要为静态变量定义存储:

#include <iostream>

struct Entity
{
    static int x,y; // <-- declares that variables exist somewhere
    
    static void print()
    {
        std::cout << x << " Yoo -- ooY " << y << std::endl;
    }
};

int Entity::x = 0; // <-- defines storage
int Entity::y = 0; // <-- defines storage

int main() {
    Entity::print();
    return 0;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多