'foo' was not declared in this scope c++

后端 未结 3 1038
醉话见心
醉话见心 2020-11-27 19:52

I\'m just learning c++ (first day looking at it since I took a 1 week summer camp years ago)

I was converting a program I\'m working on in Java to C++:



        
相关标签:
3条回答
  • 2020-11-27 20:34

    In C++, your source files are usually parsed from top to bottom in a single pass, so any variable or function must be declared before they can be used. There are some exceptions to this, like when defining functions inline in a class definition, but that's not the case for your code.

    Either move the definition of integrate above the one for getSkewNormal, or add a forward declaration above getSkewNormal:

    double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
    

    The same applies for sum.

    0 讨论(0)
  • 2020-11-27 20:40

    In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal(), the compiler needs to see the declaration:

    double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
    

    Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc or *.cpp) file. This neatly solves the problem of needing all the functions to be declared.

    0 讨论(0)
  • 2020-11-27 20:42

    In C++ you are supposed to declare functions before you can use them. In your code integrate is not declared before the point of the first call to integrate. The same applies to sum. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.

    Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable, getSkewNormal, integrate etc. have no business being in header file.

    Also SkewNormalEvalutatable e(); declaration in C++ declares a function e, not an object e as you seem to assume. The simple SkewNormalEvalutatable e; will declare an object initialized by default constructor.

    Also, you receive the last parameter of integrate (and of sum) by value as an object of Evaluatable type. That means that attempting to pass SkewNormalEvalutatable as last argument of integrate will result in SkewNormalEvalutatable getting sliced to Evaluatable. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.

    0 讨论(0)
提交回复
热议问题