Immortal Nephi <Im************@satx.rr.comwrote:
I want two objects to share variables. For example, you define two
classes A1 and A2. Class A1 and class A2 share its own variables.
Then, you define another two objects -- class B1 and class B2. Class
B1 andclass B2 have its own copy of shared variables.
Class A1 modifies class A2's variable. Then, class A2 is in turn to
modify class A1's variable.
There you go with the confusion between class and object again. If you
want two objects to share one object (variable), then try to present an
example that also talks about objects (rather than classes.) If you want
two objects to share a variable then you use pointers.
In the below program, there are three objects. Two of type A1, and one
of type int. The two former objects share the one latter object.
class A1 {
int* var;
public:
A1():var(0) { }
void set( int& v ) { var = &v; }
void modify( int v ) {
*var = v;
}
int value() const { return *var; }
void print() const {
cout << *var << '\n';
}
};
int main() {
int shared_var = 0;
A1 obj1;
A1 obj2;
obj1.set( shared_var );
obj2.set( shared_var );
assert( obj1.value() == obj2.value() );
obj1.print();
obj2.print();
obj1.modify( 12 );
assert( obj1.value() == obj2.value() );
obj1.print();
obj2.print();
}
Note: the above is generally considered poor design. You should only be
able to change an object's state by calling a public member-function on
that object, but here main can change the state of obj2 by calling a
variable on obj1.
Let me show you an example.
[example snipped]
>
Why did C++ Compiler gives an error -- error C2027: use of undefined
type 'Base2'? I aready declared class Base2 in the above of class
Base1 definition. Do you have a way to fix it?
You *declared* Base2 before Base1, but you did not *define* it. You
cannot use it until you define it.
Here is your example with the compiler error fixed.
class Base2;
class Base1 {
public:
void Set1(int a, int b); // can't use Base2 here,
// so you can't define these functions here
void Print1();
Base2 *base2_ptr;
private:
int m_Base1;
friend class Base2;
};
class Base2 {
public:
void Set2(int a, int b) {
base1_ptr->m_Base1 = b;
m_Base2 = a;
}
void Print2() {
cout << "Base1: " << base1_ptr->m_Base1 << endl;
cout << "Base2: " << m_Base2 << endl;
}
Base1 *base1_ptr;
private:
int m_Base2;
friend class Base1;
};
// now that Base2 is defined, you can define these functions
// that use Base2
void Base1::Set1(int a, int b) {
m_Base1 = a;
base2_ptr->m_Base2 = b;
}
void Base1::Print1() {
cout << "Base1: " << m_Base1 << endl;
cout << "Base2: " << base2_ptr->m_Base2 << endl;
}
int main() {
Base1 base1;
Base2 base2;
base1.base2_ptr = &base2;
base2.base1_ptr = &base1;
base1.Set1(10,20);
base1.Print1();
base2.Set2(30,40);
base2.Print2();
base1.Print1();
// Second two objects
Base1 base3;
Base2 base4;
base3.base2_ptr = &base4;
base4.base1_ptr = &base3;
base3.Set1(10,20);
base3.Print1();
base4.Set2(30,40);
base4.Print2();
base3.Print1();
}