C++通过将静态成员变量作为参数传递来初始化该变量

C++ Initializing a static member variable by passing it as a parameter?

本文关键字:变量 参数传递 初始化 静态成员 C++      更新时间:2023-10-16

我有一个静态成员变量,我想通过将它传递给一个修改自己参数的函数来初始化它,比如:

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

我能想到的唯一方法是在主函数中初始化它。我的问题是:这是唯一的方法吗?如何在.h文件中初始化它?

函数返回后,只会修改超出范围的p的副本。

要修改传入的任何变量,请使用引用参数:

 void func(Typename& p)
                // ^

静态类成员可以使用constexpr:在类声明中初始化

 class Foo {
     static constexpr Typename func();
     static constexpr Typename bar = func(); 
 };

请看这里。

您可以通过以下方式在.h文件中修改它:

#ifndef FILENAME_H
#define FILENAME_H

如果需要的话,还可以在这里包括所需的任何头,如stdio或stdlib然后编写程序/功能

void func(Typename& p);

之后,您必须创建一个.cpp文件来实现这个头(因为在头文件中您只写过程/函数,而不是实现)

#include "filename.h"
void func(Typename& p)
{
//code here,
//modifies the value of p
};

最后在您的驱动程序(主程序中,您可以通过包含.h文件来使用它)