How to use instance of one class in a method of another class?
I defined two classes class A and class B . They are completely independent.
Now I create c
as instance of class B
and d
as instance of class A
. Now I want to define the body of functionOfA
that will perform operations on c
:
class A {
public:
functionOfA();
}
class B {
...
}
A::functionOFA()
{
c.functionOfB();
}
main()
{
A d;
B c;
d.functionOfA();
}
but the compiler gives me the following error: c is not declared in this scope
A::functionOfA()
定义需要知道什么是c
实例,你可以传入B
实例:
class B;
class A
{
public:
functionOfA(const B& b) const;
};
A::functionOFA(const B& b) const
{
b.functionOfB();
}
A a;
B b;
a.functionOfA(b); // pass in B instance
In this code (your main
):
{
A a;
B b;
a.functionOfA();
}
b
is a local variable usable only within this scope. b
represents an object with automatic storage duration that exists until the execution goes out of the scope (in this case: out of your main
).
When you call the method functionOfA
, although the object b
still "lives", the functionOfA
has no means of accessing this object ~> this method needs a reference to this object (or its copy) to use it:
class A {
public:
void functionOfA(B& b) {
/* b is now accessible here, this method can also change the object b */
}
called in this manner:
A a;
B b;
a.functionOfA(b);
I recommend you to also have a look at these questions:
How to pass objects to functions in C++?
Is it better in C++ to pass by value or pass by constant reference?
Are there benefits of passing by pointer over passing by reference in C++?
and some good book might be very helpful here too:
The Definitive C++ Book Guide and List
A::functionOFA()
{
c.functionOfB(); //You cannot do this unless c is global
}
However in your case its in main
Use:
B c;
void A::functionOfA()
{
c.functionOfB();
}
OR
pass Object of B as an argument functionOfA(const B& c)
上一篇: 传递引用是传递指针的特例吗?
下一篇: 如何在另一个类的方法中使用一个类的实例?