[英]C++ Initializing a static member variable by passing it as a parameter?
I have a static member variable ,I want to initialize it by passing it to a function which modifies its own parameter ,like:我有一个静态成员变量,我想通过将它传递给一个修改自己参数的函数来初始化它,例如:
Class MyClass
{
static RECT rcRect;//The RECT structure defines the coordinates of the upper-left and lower-right corners of a rectangle.
}
GetClientRect(GetDesktopWindow(),&rcRect);
//Windows API,
//GetDesktopWindow retrieves a handle to the desktop window ,
//GetClientRect gets the coordinates of the desktop's client area ,
//and passes it to rcRECT
The only way I can think of is to initialize it in the main function .我能想到的唯一方法是在主函数中初始化它。 My question is :Is this the only way to do it?我的问题是:这是唯一的方法吗? How Can I initialize it in the .h file ?如何在 .h 文件中初始化它?
Your function will only modify a copy of p
that goes out of scope as soon the function returns.您的函数只会修改函数返回后超出范围的p
副本。
To modify any variable passed in used a reference parameter:要修改传入的任何变量,请使用引用参数:
void func(Typename& p)
// ^
Static class members can be initialized in the class declaration using constexpr
:静态类成员可以在类声明中使用constexpr
初始化:
class Foo {
static constexpr Typename func();
static constexpr Typename bar = func();
};
you can modify it in the .h file by :您可以通过以下方式在 .h 文件中修改它:
#ifndef FILENAME_H
#define FILENAME_H
you can also include any header you needed here like stdio or stdlib if you want then write the procedure / function如果需要,您还可以在此处包含您需要的任何标头,例如 stdio 或 stdlib,然后编写过程/函数
void func(Typename& p);
After that you must create a .cpp file to implement this header (because in header file you only write the procedure / function not the implementation)之后你必须创建一个 .cpp 文件来实现这个头文件(因为在头文件中你只编写过程/函数而不是实现)
#include "filename.h"
void func(Typename& p)
{
//code here,
//modifies the value of p
};
Finally in your driver (main program you can use it by include the .h file)最后在您的驱动程序中(您可以通过包含 .h 文件来使用它的主程序)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.