If I have these two sets of .cpp
and .h
files set up like this and I l want to put an add()
function in a.cpp
that adds ten integers and returns sum. Then I have class b
that will return the average but I want to use the sum of the ten integers that I got from class a
. How can I call function add()
in function average()
so it can return the sum? I don't know if this is getting my question across well, I just made this example up to try it illustrate it.
class a {
private:
int a[10];
public:
a( );
int add( int);
};
class b {
private:
int d;
public:
int average(int );
}
You can call member functions on an object of a class, not on the class itself. Creating an object is almost as creating a variable, for example a my_a;
. Then you can use the add
member function of the my_a
object as my_a.add(42)
.
If you do not need objects (but do need classes for some reason), use static member functions and variables as follows.
class MyClass {
private:
static int variable;
public:
static int accessor() { return variable; }
};
In this case, you can call the static member function without creating an instance as MyClass::accessor()
.
class A {
public:
static int add(int);
};
class B {
public:
void average(int val){
A::add(val);
// Some logic
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.