C++ 不同类别c和x2B对象之间的通信+;

C++ 不同类别c和x2B对象之间的通信+;,c++,C++,如何使对象在其他类中保持有效?下面是一个例子。 此代码将在屏幕上显示结果: 2 2 我想要的是给我这个: 2 3 换句话说,我希望objectBita(甚至整个类two)确认objectAlpha,而不是创建新对象。 有没有办法将对象Alpha包含到对象Bita中?请简单一点,因为我是初学者 #include <iostream> #include <cstdlib> #include <cstdio> #include <stdlib.h>

如何使对象在其他类中保持有效?下面是一个例子。 此代码将在屏幕上显示结果:

2
2
我想要的是给我这个:

2
3
换句话说,我希望object
Bita
(甚至整个类
two
)确认object
Alpha
,而不是创建新对象。 有没有办法将对象Alpha包含到对象Bita中?请简单一点,因为我是初学者

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

class one
{
    int a, b;
public:
    one() { a = 2; }
    int func()
    {
        return a;
    }
    void func2()
    {
        a = 3;
    }
};

class two
{
    int z, b;
public:
    void test();
};

void two::test()
{
    one Alpha;
    cout << Alpha.func() << '\n';
}

int main()
{
    one Alpha;
    cout << Alpha.func() << '\n';
    Alpha.func2();
    two Bita;
    Bita.test();
    return 0;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
一班
{
INTA,b;
公众:
one(){a=2;}
int func()
{
返回a;
}
void func2()
{
a=3;
}
};
二班
{
int z,b;
公众:
无效试验();
};
voidtwo::test()
{
一个α;

cout对象的每个实例都有自己的成员变量值。因此,当您声明两个Bita并调用Bita.test()时,test()会在其中创建自己的Alpha类对象,其值仍为2,打印该值,然后Alpha对象超出范围,并在test()完成时从堆栈中删除

你说你想在这里做的是让一类拥有所谓的静态成员变量。添加关键字static:

static int a;
然后a会按照你的意愿行事


对此的一种解释如下:

一种解决方案是通过引用传递对象,方法如下

class two
{
    int z, b;
public:
    void test(one& a);
};

void two::test(one& a)
{
    cout << a.func() << '\n';
}
因此,完整的代码将是

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

class one {
    int a, b;

public:
    one() { a = 2; }
    int func() { return a; }
    void func2() { a = 3; }
};

class two {
    int z, b;

public:
    void test(one&);
};

void two::test(one& a) {
    cout << a.func() << '\n';
}

int main() {
    one Alpha;
    cout << Alpha.func() << '\n';
    Alpha.func2();
    two Bita;
    Bita.test(Alpha);
    return 0;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
一班{
INTA,b;
公众:
one(){a=2;}
int func(){return a;}
void func2(){a=3;}
};
二班{
int z,b;
公众:
空隙试验(一次和一次);
};
无效2::测试(1&a){

不能,那是不可能的。这看起来像是某种可怕的代码气味(例如,设计错误)。你很可能是XY问题的受害者。你认为你为什么需要这个?听起来你想将
a
声明为
static
,但你的问题真的不清楚。你到底想实现什么?我想你在寻找这个:屏幕上的结果仍然是:2 2Oh是的。是2 3:)。谢谢,抱歉。所以你要做的是通过引用传递对象一..很好!还有其他方法吗,比如只在对象位中包含对象Alpha?例如,使用命令#include?如果你只想在所有代码中使用
one
的一个实例,只需使用
静态
属性和方法即可。
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

class one {
    int a, b;

public:
    one() { a = 2; }
    int func() { return a; }
    void func2() { a = 3; }
};

class two {
    int z, b;

public:
    void test(one&);
};

void two::test(one& a) {
    cout << a.func() << '\n';
}

int main() {
    one Alpha;
    cout << Alpha.func() << '\n';
    Alpha.func2();
    two Bita;
    Bita.test(Alpha);
    return 0;
}