本文介绍了C ++在类中声明静态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图声明我在另一个类B中编写的类A的静态对象,如下所示:

I'm trying to declare a static object of a class A that I wrote in a different class B, like this:

class A // just an example
{
    int x;
public:
    A(){ x = 4; }
    int getX() { return x; }
};

class B
{
    static A obj1;  // <- Problem happens here
public:
    static void start();
};

int main()
{
    B::start();
}

void B::start()
{
    int x = obj1.getX();
}

我要实现的是使B::start()中的int x等于class A中的int x(4).

What I want to achieve is to get int x in B::start() to equal int x in class A (4).

在过去的一个小时中,我尝试使用所有这些功能进行谷歌搜索,但我了解到的是C ++不允许静态对象的声明.正确吗?

I tried googling all this for the past hour and all I understood was that C++ doesn't allow static objects' declarations. Is that correct?

如果是这样,这是我的问题.如何获得相同的结果?我可以使用哪些解决方法?请记住,我的其余代码取决于B类中的函数是静态的.

If so, here's my question. How can I get the same result? What are my available workarounds? Keeping in mind that the rest of my code depends on the functions in class B to be static.

错误

谢谢!

推荐答案

您应该初始化static var,代码:

class A // just an example
{
    int x;
public:
    A(){ x = 4; }
    int getX() { return x; }
};

class B
{
    static A obj1;  // <- Problem happens here
public:
    static void start();
};

A B::obj1; // init static var

int main()
{
    B::start();
}

void B::start()
{
    int x = obj1.getX();
}

这篇关于C ++在类中声明静态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 20:41
查看更多