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文件来使用它)
相关文章:
- 如何将指针变量作为引用参数传递?
- 变量模板是否可以作为模板模板参数传递
- 是否可以将结构的成员变量作为参数传递
- C++:访问作为函数参数传递的双指针数组所指向的变量的值
- 在 c++ 模板中将变量作为参数传递
- 是否可以将变量/函数返回作为模板参数传递
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 如何将变量作为构造函数参数或函数参数传递
- 让宏将迭代参数传递到通过宏变量提供的代码体中
- 即将将引用作为函数中的参数传递以更改参数变量的值
- 是否可以在不为该数组创建变量的情况下将数组作为参数传递到函数中?
- 当将变量作为函数参数传递时,由于隐式铸造而导致的精度丧失
- 如果结构作为递归函数中的参数传递,如何初始化结构的成员变量
- C 11-当我将局部变量作为参数传递到线程中时,它是否安全
- 如果我有一个将指针变量作为输入的函数,有没有办法将函数作为参数传递
- 为什么我无法访问作为参数传递到函数中的基类的受保护成员变量?
- 如何强制转换变量成员以将其作为函数的引用参数传递
- 直接访问成员变量或作为参数传递
- 使用变量参数列表为传递的引用赋值(VS2010中出错)
- 将变量作为模板参数传递