繁体   English   中英

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

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

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

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 文件来使用它的主程序)

暂无
暂无

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

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