Home > Backend Development > C++ > Why Does Accessing a Static Class Variable from a Non-Static Method in C Cause an Undefined Reference?

Why Does Accessing a Static Class Variable from a Non-Static Method in C Cause an Undefined Reference?

Linda Hamilton
Release: 2024-12-27 05:31:13
Original
338 people have browsed it

Why Does Accessing a Static Class Variable from a Non-Static Method in C   Cause an Undefined Reference?

Accessing Static Class Variable from Non-Static Method

In C , when encountering an undefined reference to a static variable, such as in the given code snippet, the issue usually lies in the lack of a definition for that variable.

In the example provided, where the code attempts to access the static variable x from within the non-static method foo, it's important to note that foo is not a static function. Therefore, to resolve this issue, a definition for Helloworld::x must be provided outside of the class definition.

int Helloworld::x = 0; // Provide an initial value or leave uninitialized
Copy after login

Once the static variable is defined, the non-static method foo can access and modify it without requiring foo to be static itself.

void Helloworld::foo() {
     Helloworld::x = 10;
}
Copy after login

By providing a definition for the static member variable, the compiler can locate its memory address and resolve the undefined reference.

The above is the detailed content of Why Does Accessing a Static Class Variable from a Non-Static Method in C Cause an Undefined Reference?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template