i would like to run a function method of a class inside another function method of another class. I wrote the following code as an example and it compiles and return the expected values. My question is if this is the correct way of preforming a computation of class method inside another class method...
Regards
#include <iostream>
class CBoo {
public:
CBoo();
void Test();
void Plot();
private:
int b;
};
CBoo::CBoo() {
b = 3;
}
void CBoo::Test() {
b++;
}
void CBoo::Plot() {
std::cout << "b: " << b << std::endl;
}
class CFoo {
public:
CFoo();
void Test( CBoo &Boo );
voi开发者_如何转开发d Plot();
private:
int a;
};
CFoo::CFoo() {
a = 3;
}
void CFoo::Test( CBoo &Boo ) {
for ( int i = 0 ; i < 10 ; i++ ) {
a++;
Boo.Test();
}
}
void CFoo::Plot() {
std::cout << "a: " << a << std::endl;
}
int main( ) {
CFoo Foo;
CBoo Boo;
Foo.Test( Boo );
Foo.Plot();
Boo.Plot();
return 0;
}
There are two straightforward ways to do this. One of them, the one you chose, is to pass an external class object to another object method. The other is to encapsulate an object inside of another object and to call it directly from a method of the enclosing class.
There may be more esoteric ways of doing this, but the one you chose is perfectly reasonable. Which option you choose is based on the architecture of your program.
Looks perfectly reasonable to me.
The method that you are using is not a class method. In general, class/static method means the methods that are not associated with any particular instance of the class, rather they are associated with class itself. In C++, static is used for this.
The method you are using is called instance method. The way you have used it is perfectly fine. And instead of passing a parameter you can have a reference in the class as pointed by Greg. It all depends on your needs. If the method is required only in one method or if you to use different instances of Boo
is CFoo.Test
then you should pass them as parameter. But if you need only one instance of Boo
all the time then you can create that in CFoo
and use that in all methods. What you will do is dependent on your need.
The only objection that I have about your code is the naming of variable. The convention is to use lower case letter to denote objects/methods and upper case to denote class. So parameter Boo
should be named boo
.
精彩评论