简体   繁体   中英

Call to methods contained in class in C++ with variables and functions in the main

Below is the situation I'm encountering. I need to call a method (namely manip_A()) contained in a class (ManipFunction), some parameters being provided in the main function. Those parameters are variables (some doubles) and a function (namely func). Can someone help? Thankyou.

// manip.hpp
class ManipFunction
{
// for example ..
private:
    // Initialization function ...

    // Copy constructors ...

    // Core functions ...
    double manip_A();
    double manip_B();


public:
    // Public member data ...
    ...
    // Constructors ...
    ...
    // Destructors ...
    ...
    // Assignment operator ...
};

.

// manip.cpp
#include"manip.hpp"

// Core functions
double ManipFunction::manip_A() const
{
    // Apply manip_A() to the function and parameters provided in manip_test.cpp
}

double ManipFunction::manip_B() const
{
    // Apply manip_B() to the function and parameters provided in manip_test.cpp
}

// Initialisation
...
// Copy constuctor
...
// Destructor
...
// Deep copy
...
}

.

// manip_test.cpp

#include<iostream>
// Other required system includes

int main()
{
    double varA = 1.0;
    double VarB = 2.5;

    double func (double x) {return x * x};

    double manip_A_Test = ManipFunction::manip_A(func, varA, VarB);

    std::cout << "Result of Manip_A over function func: " << manip_A_Test <<  endl;

        return 0;
}

OK several misunderstandings here.

1) Functions inside functions are not legal C++.

int main()
{
    ...
    double func (double x) {return x * x};
    ...
}

This is not allowed. Move func outside of main. Also the trailing ; is not legal.

2) To call a ManipFunction method, you need a ManipFunction object . Your code doesn't provide that.

int main()
{
    ...
    ManipFunction mf; // a ManipFunction object
    mf.manip_A(func, varA, VarB); // call the manip_A method on the ManipFunction object
    ...
}

3) Although you say that you want manip_A to have parameters, you haven't declared any. Here I've given manip_A two parameters, both of type double .

class ManipFunction
{
    double manip_A(double x, double y);
    ...
};

4) Although you say you want to call manip_A from inside main, in your code you have declared manip_A as private . It must be public if you want to call it directly from main.

Finally I'd just say that's it probably better to post your real code, instead of the made up code I think you've posted.

Hope this helps

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM