我怎样才能让对象在另一个类中保持有效?以下是一个例子。 这段代码会在屏幕上显示:
2
2
我想要的是给我这个:
2
3
换句话说,我希望对象Bita
(甚至整个类two
)来确认对象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;
}
答案 0 :(得分:1)
对象的每个实例都有自己的成员变量值。因此,当你声明两个Bita,并调用Bita.test()时,test()在其内部创建自己的类Alpha对象,其自身的值仍为2,打印出来,然后该Alpha对象熄灭范围的,并在test()完成时从堆栈中删除。
你在这里要做的就是让第一类拥有所谓的静态成员变量。添加关键字static:
static int a;
然后一个意志就像你想要的那样。
对此的一种解释是:http://www.learncpp.com/cpp-tutorial/811-static-member-variables/
答案 1 :(得分:0)
一种解决方案是通过引用方法two::test
像这样传递对象
class two
{
int z, b;
public:
void test(one& a);
};
void two::test(one& a)
{
cout << a.func() << '\n';
}
然后在main
Bita.test(Alpha);
所以完整的代码将是
#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;
}