[英]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.