全局声明类对象,但不带参数 [英] Declare class object globally but without parameters

查看:69
本文介绍了全局声明类对象,但不带参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我的情况:我有一个类foo驻留在foo.cpp中,其头文件foo.h包含在main.cpp中。我需要能够将foo对象声明为main.cpp中的全局变量,以便它对main.cpp中的所有函数都可用,而不必每次都传递对其的引用。问题是,foo的构造函数需要一个变量,直到main.cpp中的main函数中途才从用户检索该变量。我以为可以这样做:

So here's my situation: I have a class foo residing in foo.cpp with header file foo.h included in my main.cpp. I need to be able to declare a foo object as a global variable in main.cpp so that it is available to all functions within main.cpp without having to pass a reference to it every time. The problem is, foo's constructor requires a variable which isn't retrieved from the user until halfway through the main function in main.cpp. I thought I could do this this way:

static foo myFoo;

作为主函数上方的全局变量,然后在从用户检索必要的数据后(称它为变量),我可以这样称呼:

As a global variable above the main function, then after the necessary data is retrieved from the user (let's call it "variable"), I could call:

myFoo = new foo(variable);

但是我遇到了一个错误:

I'm getting an error however with this:


错误:没有匹配的函数可以调用'foo :: foo()'

error: no matching function for call to ‘foo::foo()’

static foo myFoo;

引用行,所以基本上是说我正在尝试声明一个实例foo的构造函数采用零参数(如果没有)。

So it's basically saying that I'm trying to declare an instance of foo with a constructor taking zero arguments, when there is none.

所以我的问题是:有没有一种方法可以将foo之外的标签myFoo声明为全局变量,以便程序进行编译,然后可以将其实例化。使用构造函数并传递变量?

So my question is: Is there a way to declare a label myFoo out of foo as a global variable so that the program compiles, and then later it can actually be instantiated using the constructor with a variable passed?

我知道我可以做这样的事情:

I know I could just do something like this:

string temp = "";
static foo myFoo(temp);

在main()上方,然后定义一些可以在哪里执行的函数

above main() and then have some function defined where I could do

myFoo.setVar(variable);

我需要的时候。对我来说,这是非常丑陋的,需要包括setVar函数,该函数除了规避此问题外没有其他实际目的。有想法吗?

when I needed to. To me this is very ugly and necessitates the inclusion of the function setVar which has no tangible purpose other than to circumvent this very issue. Thoughts?

推荐答案

一种选择是使静态实例成为指针:

One option you have is to make your static instance a pointer:

static foo *myFoo = NULL;

// Later...
myFoo = new foo(variable);

或者您可能想使用默认构造函数并进行 Init

Or you may want to use a default constructor and make an Init method instead.

static foo myFoo;

// Later...
myFoo.Init( variable );

暴露变量时,未将其定义为静态。删除 static 关键字,并在标题的声明中使用 extern

When you're exposing a variable, you don't define it as static. Remove the static keyword and use extern in the header's declaration.

这篇关于全局声明类对象,但不带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆