简体   繁体   English

VC ++类。 静态变量错误未解决的外部符号

[英]VC++ Classes. Static variables error unresolved external symbol

I have this error that keeps haunting me in all of my programs that is probably just me overlooking something. 我有这个错误,使我在所有程序中一直困扰着我,而这可能只是我忽略了某些东西。

code snippet where this error appears: 出现此错误的代码段:

class myClass {
private:
    int x;
public:
    static int getX() {
        x = 10;
        return x;
    }
};

int main() {
    cout << myClass::getX() << endl;
    return 0;
}

The error I am getting says : 我得到的错误说:

error unresolved external symbol 错误未解决的外部符号

What is causeing this or what is wrong with my code? 是什么原因造成的或我的代码有什么问题?

A static member function of class foo is not associated with an object of that class (doesn't have the this pointer). foo static成员函数未与该类的对象关联(没有this指针)。

And how can you access the member variables of foo without an object? 又如何在没有对象的情况下访问foo的成员变量? Unless they are static themselves, you can't. 除非它们本身是static ,否则不能。

You must create an instance of foo first. 您必须先创建foo的实例。

In your case: 在您的情况下:

static int myClass::getX() {
    myClass obj;
    obj.x = 10;
    return obj.x;
}

Inside a class you are trying to access the non-static variable using the static method which will not work. 在类内部,您尝试使用无法使用的静态方法访问非静态变量。 You can turn the private member variable x into static and initialize it outside the class. 您可以将私有成员变量x转换为static并在类外部对其进行初始化。 Then your example can look like: 然后您的示例如下所示:

#include <iostream>
class myClass {
private:
    static int x;
public:
    static int getX()
    {
        x = 10;
        return x;
    }
};
int myClass::x = 0;

int main() {
    std::cout << myClass::getX() << std::endl;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM