我试图通过在类B中定义/声明的函数来更改类A的变量的值。我尝试了不止一种方法,但没有找到一种有效的方法。
File : myheader.h
class A {
public:
int x;
};
class B:public A
{
public:
void Print(void)
{
A::x=0;
}
};
好的,主要是...
#include <iostream>
#include "myheader.h"
using namespace std;
A mya;
B myb;
int main(){
mya.x=10;
cout<<mya.x<<endl; //That will print 10
myb.Print();
cout<<mya.x<<endl; //That will print also 10, i want it to print 0
return 0;
}
分别显示10和10。我想通过类B的函数访问类A中的变量x。我找不到能起作用的东西...
最佳答案
在您的代码中,mya
和myb
是单独的实例。两个完全不同的对象。myb.Print()
更改x
对象(myb
)上myb.x
的值,但对mya
无任何作用。尝试用最后一行myb.x
打印cout
:
cout << myb.x << endl;
------编辑(回应您的评论)------
考虑以下代码。
使
B
实例(在本例中为Cat
)在A
实例(在本例中为Animal
)上运行的方法是将对A实例的引用传递给B实例( tom.eats( jerry );
)。在此示例中,实例为
tom
,jerry
和spike
。与您的mya
和myb
相似。class Animal {
public:
Animal() { _alive = true; }
bool isAlive() { return _alive; } // getter
void setAlive( bool value ) { _alive = value; } // setter
bool _alive;
};
class Cat : public Animal {
public:
void eats( Animal &animal ) {
animal.setAlive( false );
}
};
class Mouse : public Animal { };
int main( int argc, char **argv ) {
Cat tom;
Mouse jerry;
Animal spike; // a dog, but could be any animal
cout << tom.isAlive() << endl; // true, the cat named "tom" is alive
cout << jerry.isAlive() << endl; // true, the mouse named "jerry" is alive
cout << spike.isAlive() << endl; // true, the dog named "spike" is alive
tom.eats( jerry ); // the cat eats the mouse. so sad.
// the cat can do this because Mouse is also an Animal
cout << tom.isAlive() << endl; // true, the cat named "tom" is alive
cout << jerry.isAlive() << endl; // false, the mouse named "jerry" is not alive
cout << spike.isAlive() << endl; // true, the dog named "spike" is alive
tom.eats( spike ); // the cat eats the dog. impressive.
// the cat can do this because spike is an Animal
cout << tom.isAlive() << endl; // true, the cat named "tom" is alive
cout << jerry.isAlive() << endl; // false, the mouse named "jerry" is not alive
cout << spike.isAlive() << endl; // false, the dog named "spike" is not alive
tom.eats( tom ); // the cat eats itself. this cat is really hungry.
// the cat can do this because Cat is an Animal
cout << tom.isAlive() << endl; // false, the cat named "tom" is not alive
cout << jerry.isAlive() << endl; // false, the mouse named "jerry" is not alive
cout << spike.isAlive() << endl; // false, the dog named "spike" is not alive
spike.eats( tom ); // error, Animal class has no eats() method so
// this won't compile
}