我可以在 C++ 中全局声明类对象吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18823331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I declare class object globally in c++?
提问by jpm
class Foo {
public:
Foo(int a, int b);
Foo();
};
Foo foo;
int main(){
foo(1,3);
}
Is this the correct thing to do, if I am using a global class Foo?
如果我使用全局类 Foo,这是正确的做法吗?
If no, can you please which is the correct way to doing this?
如果不是,你能请教这是正确的方法吗?
NOTE: I want the class object globally.
注意:我想要全局的类对象。
采纳答案by Some programmer dude
Yes, you can declare a global variable of any type, class or not.
是的,您可以声明任何类型、类与否的全局变量。
No, you can't then "call" the constructor again inside a function to initialize it. You can however use the copy assignment operator to do it:
不,您不能在函数内部再次“调用”构造函数来初始化它。但是,您可以使用复制赋值运算符来执行此操作:
Foo foo;
int main()
{
foo = Foo(1, 3);
}
Or you can have a "setter" function that is used to set or reinitialize the object.
或者您可以使用“setter”函数来设置或重新初始化对象。
By the way, and depending on the data in the class, you might want to read about the rule of three.
顺便说一句,根据类中的数据,您可能想了解三的规则。
回答by Kerrek SB
It's certainly possible to have global objects. The correct way in your case is:
拥有全局对象当然是可能的。您的情况的正确方法是:
Foo foo(1, 3);
int main()
{
// ...
}