Error prototype for does not match any in class

Hi, New to c++ and have an error that I cannot resolve. Thinking I've just made a very basic mistake and cannot see it. The error is 'prototype f
  • Home
  • Forum
  • General Programming Boards
  • C++ Programming
  • Prototype for » does not match any in class error

  1. 04-07-2021


    #1

    ScottChegg is offline


    Registered User


    Question Prototype for » does not match any in class error

    Hi,

    New to c++ and have an error that I cannot resolve. Thinking I’ve just made a very basic mistake and cannot see it.

    The error is «prototype for ‘void Menu::newItem(std::string, std::string, int)’ does not match any in class ‘Menu'»

    I am certain they match, all similar stack overflow questions were trying to pass too many variables or had different return types which is why this seems so strange.

    menu.h

    Code:

    #ifndef MENU_H
    #define MENU_H
    
    
    #include <string>
    using std::string;
    #include <iostream>
    #include "item.h"
    //#define MAXLEN 20
    
    
    class Menu {
    private:
            string _fName;
            string _mName;
            Item _db[20]; 
            int _nElems;
    public:
            Menu(string mName) : _fName(""), _mName(mName), _nElems(0) {  };
           
            void newItem(string category, string description, int price);
            
            void display();
            
    };
    #endif

    menu.cpp

    Code:

    #include "menu.h"
    #include <string>
    using std::string;
    #include <iostream>
    using std::cout;
    using std::endl;
    
    
    
    
    void Menu::newItem(string category, string description, int price){
            _db[_nElems] = Item(category, description, price);
            _nElems++;
    }
    
    
    void Menu::display(){
            string div = 
            "+--+-------+---------------------------------+-----+n";
            cout << div <<
            "|No|Cat.   |Description                      |Price|n" << div;
            for(int i = 0; i < _nElems; i++) {
                    _db[i].display(i);
            }
            cout << div;
    }

    Any help would be greatly appreciated!


  2. 04-07-2021


    #2

    laserlight is offline


    C++ Witch

    laserlight's Avatar


    You’re right: they match.

    It may make no difference, but I suggest that you remove the using declaration from the header file: fully qualify std::string there instead. In the source file, move the using declaration to after the last header inclusion. The reason is that using declarations at file scope in a header can change the meaning of code in the files that include the header, and using declarations before a header can change the meaning of code in the included header.

    Other things to tell us: which line does the error reference? What’s in item.h?

    Last edited by laserlight; 04-07-2021 at 04:42 AM.

    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)

    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.

    Look up a C++ Reference and learn How To Ask Questions The Smart Way


  3. 04-07-2021


    #3

    ScottChegg is offline


    Registered User


    Unfortunately your suggestions made no difference.

    Quote Originally Posted by laserlight
    View Post

    Other things to tell us: which line does the error reference? What’s in item.h?

    in menu.cpp:

    Code:

     void Menu::newItem(std::string category, std::string description, int price){

    and in menu.h ([ERROR] candidate is: void Menu::newItem()):

    Code:

             void newItem(std::string category, std::string description, int price);


  4. 04-07-2021


    #4

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    Which compiler/IDE are you using?


  5. 04-07-2021


    #5

    ScottChegg is offline


    Registered User


    Quote Originally Posted by Salem
    View Post

    Which compiler/IDE are you using?

    Dev C++


  6. 04-07-2021


    #6

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    Are you talking about the archaic «Bloodshed» Dev-C++ or the somewhat up to date «Orwell» Dev-C++.

    Because the bloodshed one is about 20 years out of date.

    Dev-C++ download | SourceForge.net


  7. 04-07-2021


    #7

    ScottChegg is offline


    Registered User


    I’m embarrassed to say the bloodshed one. It has been pushed quite heavily on my course. Will see if the code compiles on another IDE now.

    EDIT: I’m actually using the version linked above.

    Last edited by ScottChegg; 04-07-2021 at 06:22 AM.


  8. 04-07-2021


    #8

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    You’re using the Orwell one and it doesn’t work?

    I commented out Item (not that it should matter for the purpose of the exercise), and it compiles just fine here

    Code:

    $ cat menu.h
    #ifndef MENU_H
    #define MENU_H
     
     
    #include <string>
    using std::string;
    #include <iostream>
    //#include "item.h"
    //#define MAXLEN 20
     
     
    class Menu {
    private:
            string _fName;
            string _mName;
            //Item _db[20]; 
            int _nElems;
    public:
            Menu(string mName) : _fName(""), _mName(mName), _nElems(0) {  };
            
            void newItem(string category, string description, int price);
             
            void display();
             
    };
    #endif
    $ cat menu.cpp
    #include "menu.h"
    #include <string>
    using std::string;
    #include <iostream>
    using std::cout;
    using std::endl;
     
     
     
     
    void Menu::newItem(string category, string description, int price){
            //_db[_nElems] = Item(category, description, price);
            _nElems++;
    }
     
     
    void Menu::display(){
            string div = 
            "+--+-------+---------------------------------+-----+n";
            cout << div <<
            "|No|Cat.   |Description                      |Price|n" << div;
            for(int i = 0; i < _nElems; i++) {
                    //_db[i].display(i);
            }
            cout << div;
    }
    $ g++ -c menu.cpp


  9. 04-08-2021


    #9

    ScottChegg is offline


    Registered User


    Quote Originally Posted by Salem
    View Post

    You’re using the Orwell one and it doesn’t work?

    I commented out Item (not that it should matter for the purpose of the exercise), and it compiles just fine here

    Yes, definitely using Orwell version 5.11.

    I also managed to get the code to compile today by moving the menu constructor out of the header file. Not sure how this error occurred and I’m not sure why it has gone away.

    If I had to guess I’d say the error occurred as I updated the newItem function and the compiler still expected to see the old parameters? Still, I don’t think this explains why it disappeared today once I moved the constructor.

    Regardless thanks for the help!


Popular pages

  • Exactly how to get started with C++ (or C) today
  • C Tutorial
  • C++ Tutorial
  • 5 ways you can learn to program faster
  • The 5 Most Common Problems New Programmers Face
  • How to set up a compiler
  • 8 Common programming Mistakes
  • What is C++11?
  • Creating a game, from start to finish

Recent additions subscribe to a feed

  • How to create a shared library on Linux with GCC — December 30, 2011
  • Enum classes and nullptr in C++11 — November 27, 2011
  • Learn about The Hash Table — November 20, 2011
  • Rvalue References and Move Semantics in C++11 — November 13, 2011
  • C and C++ for Java Programmers — November 5, 2011
  • A Gentle Introduction to C++ IO Streams — October 10, 2011

Similar Threads

  1. Replies: 2

    Last Post: 03-15-2019, 12:57 PM

  2. Replies: 19

    Last Post: 04-05-2016, 10:54 AM

  3. Replies: 3

    Last Post: 12-03-2004, 03:37 PM

  4. Replies: 3

    Last Post: 04-01-2004, 02:34 PM

  5. Replies: 4

    Last Post: 02-05-2003, 08:25 PM

Tags for this Thread

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Проблема с классом
    , Класс в отдельном файле компилируется с ошибкой

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    03.11.12, 08:24

      Здравствуйте!
      Пытаюсь объявить класс в отдельном файле, но при компиляции получаю ошибку.

      ExpandedWrap disabled

        //main.cpp

        #include «test.h»

        #include <iostream>

        int main()

        {

            Test_class test;

            test.message();

            test.message2();

            test.message3();

            system(«pause»);

        }

      ExpandedWrap disabled

        //test.cpp

        #include <iostream>

        using namespace std;

        #include «test.h»

        Test_class::message()

        {

            cout << «Message number 1» << endl;

        }

        Test_class::message2()

        {

            cout << «Message number 2» << endl;

        }

        Test_class::message3()

        {

            cout << «Message number 3» << endl;

        }

      ExpandedWrap disabled

        //test.h

        class Test_class

        {

            public:

                void message();

                void message2();

                void message3();

        };

      Компилирую в dev c++
      Ошибка:
      prototype for `int Test_class::message()’ does not match any in class `Test_class’

      А если сделать в таком варианте всё работает:

      ExpandedWrap disabled

        //main.cpp

        #include «test.h»

        #include <iostream>

        int main()

        {

            Test_class test;

            test.message();

            test.message2();

            test.message3();

            system(«pause»);

        }

      ExpandedWrap disabled

        //test.h

        #include <iostream>

        using namespace std;

        class Test_class

        {

            public:

                void message()

                {

                    cout << «Message number 1» << endl;

                }

                void message2()

                {

                    cout << «Message number 2» << endl;

                }

                void message3()

                {

                    cout << «Message number 3» << endl;

                }

        };


      Adil



      Сообщ.
      #2

      ,
      03.11.12, 08:45

        Цитата Fe_DoS @ 03.11.12, 08:24

        ExpandedWrap disabled

          //test.cpp

          #include <iostream>

          using namespace std;

          #include «test.h»

          Test_class::message()

          {

              cout << «Message number 1» << endl;

          }

          Test_class::message2()

          {

              cout << «Message number 2» << endl;

          }

          Test_class::message3()

          {

              cout << «Message number 3» << endl;

          }

        тип возвращаемых значений — void’ы — то допиши к методам


        Fe_DoS



        Сообщ.
        #3

        ,
        03.11.12, 09:07

          Adil, я исправил test.cpp, но теперь появилась другая ошибка.
          multiple definition of `Test_class::message()’


          Adil



          Сообщ.
          #4

          ,
          03.11.12, 09:18

            Ну так test.h у тебя, наверно, от второго варианта остался. Сделай его как в первом варианте — просто объявления методов.


            Fe_DoS



            Сообщ.
            #5

            ,
            03.11.12, 09:33

              Сейчас код имеет такой вид:

              ExpandedWrap disabled

                //main.cpp

                #include «test.h»

                #include <iostream>

                int main()

                {

                    Test_class test;

                    test.message();

                    test.message2();

                    test.message3();

                    system(«pause»);

                }

              ExpandedWrap disabled

                //test.cpp

                #include <iostream>

                using namespace std;

                #include «test.h»

                void Test_class::message()

                {

                    cout << «Message number 1» << endl;

                }

                void Test_class::message2()

                {

                    cout << «Message number 2» << endl;

                }

                void Test_class::message3()

                {

                    cout << «Message number 3» << endl;

                }

              ExpandedWrap disabled

                //test.h

                class Test_class

                {

                    public:

                        void message();

                        void message2();

                        void message3();

                };

              при этом вылетают ошибки:
              multiple definition of `Test_class::message()’
              first defined here
              multiple definition of `Test_class::message2()’
              first defined here
              multiple definition of `Test_class::message3()’
              first defined here
              ld returned 1 exit status
              [Build Error] [test.exe] Error 1


              Adil



              Сообщ.
              #6

              ,
              03.11.12, 11:31

                Где-то ты меня или себя обманываешь. Должно собираться.


                Fe_DoS



                Сообщ.
                #7

                ,
                03.11.12, 11:56

                  Проблема решилась, но причина так и осталась для меня загадкой.
                  Я создал новый проект, но класс и методы писал не вручную, а добавил их на вкладке классы и получил код:

                  ExpandedWrap disabled

                    //main.cpp

                    #include <conio.h>

                    #include «test_class.h»

                    #include <iostream>

                    using namespace std;

                    int main()

                    {

                        Test_class test;

                        test.message();

                        test.message2();

                        test.message3();

                        system(«pause»);

                    }

                  ExpandedWrap disabled

                    //test_class.cpp

                    // Class automatically generated by Dev-C++ New Class wizard

                    #include «test_class.h» // class’s header file

                    #include <iostream>

                    using namespace std;

                    // No description

                    void Test_class::message()

                    {

                        cout << «Message number 1» << endl;

                    }

                    // No description

                    void Test_class::message2()

                    {

                        cout << «Message number 2» << endl;

                    }

                    // No description

                    void Test_class::message3()

                    {

                        cout << «Message number 3» << endl;

                    }

                  ExpandedWrap disabled

                    //test_class.h

                    // Class automatically generated by Dev-C++ New Class wizard

                    #ifndef TEST_CLASS_H

                    #define TEST_CLASS_H

                    /*

                     * No description

                     */

                    class Test_class

                    {

                        public:

                            // No description

                            void message3();

                            // No description

                            void message2();

                            // No description

                            void message();

                    };

                    #endif // TEST_CLASS_H

                  Всё работает, а первый вариант продолжает выдавать ошибку…
                  Вывод: Dev C++ в корзину.


                  Kray74



                  Сообщ.
                  #8

                  ,
                  03.11.12, 12:20

                    В первом случае не было include guard в test.h


                    Adil



                    Сообщ.
                    #9

                    ,
                    03.11.12, 12:40

                      Сходу собрался первый вариант в 2008ой студии, без include guard. Да и нужны эти guard’ы только на этапе компиляции, их отсутствие не должно приводить к ошибке при линковке.


                      Fe_DoS



                      Сообщ.
                      #10

                      ,
                      03.11.12, 12:40

                        Да, но и без include guard должно работать.

                        0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                        0 пользователей:

                        • Предыдущая тема
                        • C/C++: Общие вопросы
                        • Следующая тема

                        Рейтинг@Mail.ru

                        [ Script execution time: 0,0349 ]   [ 16 queries used ]   [ Generated: 9.02.23, 15:03 GMT ]  

                        1
                        2
                        3
                        4
                        5
                        6
                        7
                        8
                        9
                        10
                        11
                        12
                        13
                        14
                        15
                        16
                        17
                        18
                        19
                        20
                        21
                        22
                        23
                        24
                        25
                        26
                        27
                        28
                        29
                        30
                        31
                        32
                        33
                        34
                        35
                        36
                        37
                        38
                        39
                        40
                        41
                        42
                        43
                        44
                        45
                        46
                        47
                        48
                        49
                        50
                        51
                        52
                        53
                        54
                        55
                        56
                        57
                        58
                        59
                        60
                        61
                        62
                        63
                        64
                        65
                        66
                        67
                        68
                        69
                        70
                        71
                        72
                        73
                        74
                        75
                        76
                        77
                        78
                        79
                        80
                        81
                        82
                        83
                        84
                        85
                        86
                        87
                        88
                        89
                        90
                        91
                        92
                        93
                        94
                        95
                        96
                        97
                        98
                        99
                        100
                        101
                        102
                        103
                        104
                        105
                        106
                        107
                        108
                        109
                        110
                        111
                        112
                        113
                        114
                        115
                        116
                        117
                        118
                        119
                        120
                        121
                        122
                        123
                        124
                        125
                        126
                        127
                        128
                        129
                        130
                        131
                        132
                        133
                        134
                        135
                        136
                        137
                        138
                        139
                        140
                        141
                        142
                        143
                        144
                        145
                        146
                        147
                        148
                        149
                        150
                        151
                        152
                        153
                        154
                        155
                        156
                        157
                        158
                        159
                        160
                        161
                        162
                        163
                        164
                        165
                        166
                        167
                        168
                        169
                        170
                        171
                        172
                        173
                        174
                        175
                        176
                        177
                        178
                        179
                        180
                        181
                        182
                        183
                        184
                        185
                        186
                        187
                        188
                        189
                        190
                        191
                        192
                        193
                        194
                        195
                        196
                        197
                        198
                        199
                        200
                        201
                        202
                        203
                        204
                        205
                        206
                        207
                        208
                        209
                        210
                        211
                        212
                        213
                        214
                        215
                        216
                        217
                        218
                        219
                        220
                        221
                        222
                        223
                        224
                        225
                        226
                        227
                        228
                        229
                        230
                        231
                        232
                        233
                        234
                        235
                        236
                        237
                        238
                        239
                        240
                        241
                        242
                        243
                        244
                        245
                        246
                        247
                        248
                        249
                        250
                        251
                        252
                        253
                        254
                        255
                        256
                        257
                        258
                        259
                        260
                        261
                        262
                        263
                        264
                        265
                        266
                        267
                        268
                        269
                        270
                        271
                        272
                        273
                        274
                        275
                        276
                        277
                        278
                        279
                        280
                        281
                        282
                        283
                        284
                        285
                        286
                        287
                        288
                        289
                        290
                        291
                        292
                        293
                        294
                        295
                        296
                        297
                        298
                        299
                        300
                        301
                        302
                        303
                        304
                        305
                        306
                        307
                        308
                        309
                        310
                        311
                        312
                        313
                        314
                        315
                        316
                        317
                        318
                        319
                        320
                        321
                        322
                        323
                        324
                        325
                        326
                        327
                        328
                        329
                        330
                        331
                        332
                        333
                        334
                        335
                        336
                        337
                        338
                        339
                        340
                        341
                        342
                        343
                        344
                        345
                        346
                        347
                        348
                        349
                        350
                        351
                        352
                        353
                        354
                        355
                        356
                        357
                        358
                        359
                        360
                        361
                        362
                        363
                        364
                        365
                        366
                        367
                        368
                        369
                        370
                        371
                        372
                        373
                        374
                        375
                        376
                        377
                        378
                        379
                        380
                        381
                        382
                        383
                        384
                        385
                        386
                        387
                        388
                        389
                        390
                        391
                        392
                        393
                        394
                        395
                        396
                        397
                        398
                        399
                        400
                        401
                        402
                        403
                        404
                        405
                        406
                        407
                        408
                        409
                        410
                        411
                        412
                        413
                        414
                        415
                        416
                        417
                        418
                        419
                        420
                        421
                        422
                        423
                        424
                        425
                        426
                        427
                        428
                        429
                        430
                        431
                        432
                        433
                        434
                        435
                        436
                        437
                        
                        ----------------------------------------bspline.cc--------------------------------------------
                         
                        #include "message.h"
                        #include "parametermap.h"
                        #include "constants.h"
                        #include "utils.h"
                        #include "linalg.h"
                        #include "lsqrinvert.h"
                        #include "bspline_imager1d.h"
                         
                        using namespace TNT;
                        using namespace std;
                         
                        #define __USE_GSL__
                         
                        #define __IMAGER_EPSILON 1e-10
                        #define __TYPICAL_SOURCE_SCALE__ 1e-4 //in fm^-3
                         
                         
                        //---------------- Read ----------------------------
                        bool CBasisSplineImager1d::Read( const parameterMap& m ){
                         
                            CBasisFuncImager1d::Read( m );
                            qscale                      = parameter::getD(m,"qscale",50.);
                        //    spline_degree               = parameter::getI(m,"spline_degree",3);
                            knot_tolerance              = parameter::getD(m,"knot_tolerance",1e-2);
                            knot_init_scheme            = parameter::getS(m,"knot_init_scheme","default");
                            optimize_knots              = parameter::getB(m,"optimize_knots",false);
                            if (optimize_knots) {
                                optimize_knots_max_iter                 = parameter::getB(m,"optimize_knots_max_iter",optimize_knots_max_iter);
                                optimize_knots_minimizer_func_weight    = parameter::getB(m,"optimize_knots_minimizer_func_weight",optimize_knots_minimizer_func_weight);
                                optimize_knots_coellesce_knot_tol       = parameter::getB(m,"optimize_knots_coellesce_knot_tol",optimize_knots_coellesce_knot_tol);
                                optimize_knots_simplex_min_size         = parameter::getB(m,"optimize_knots_simplex_min_size",optimize_knots_simplex_min_size);
                            }
                            vector< double > empty_vec(0);
                            if (knot_init_scheme == "user_defined_collocation_points") {
                                colloc_pts = parameter::getV(m,"user_collocation_points",empty_vec);
                            }
                            if (knot_init_scheme == "user_defined_knots") {
                                user_knots = parameter::getV(m,"user_knots",empty_vec);
                            }
                            return true;
                        }
                         
                        //--------------- Write -----------------------------
                        // not used much except for diagnostics, so write everything!
                        bool CBasisSplineImager1d::Write( parameterMap& m ){
                         
                            CBasisFuncImager1d::Write( m );
                            parameter::set(m,"qscale",qscale);
                        //    parameter::set(m,"spline_degree",spline_degree);
                            parameter::set(m,"knot_tolerance",knot_tolerance);
                            parameter::set(m,"knot_init_scheme",knot_init_scheme);
                            parameter::set(m,"optimize_knots",optimize_knots);
                            parameter::set(m,"optimize_knots_max_iter",optimize_knots_max_iter);
                            parameter::set(m,"optimize_knots_minimizer_func_weight",optimize_knots_minimizer_func_weight);
                            parameter::set(m,"optimize_knots_coellesce_knot_tol",optimize_knots_coellesce_knot_tol);
                            parameter::set(m,"optimize_knots_simplex_min_size",optimize_knots_simplex_min_size);
                            parameter::set(m,"user_collocation_points",colloc_pts);
                            parameter::set(m,"user_knots",user_knots);
                            return true;
                        }
                            
                        //---------------- convertCorrelationToSource ----------------------------
                        //! function that manages the imaging
                        [B]"!!!!!"[/B]
                        bool CBasisSplineImager1d::convertCorrelationToSource( const CCorrFtn1dHisto& corrin, CSourceFtnBase& souout, const parameterMap& m ){
                         
                            CBasisSpline1d* souPtr = dynamic_cast<CBasisSpline1d*>(&souout);
                            if (souPtr==NULL) throw MESSAGE<<"Source argument must derive from CBasisSpline1d"<<ENDM_FATAL;
                            bool result = CBasisFuncImager1d::convertCorrelationToSource( corrin, souout, m );
                            if (optimize_knots && result) do_optimal_knots( *souPtr ); 
                            return result;
                        }
                         
                        //---------------- convertSourceToCorrelation ----------------------------
                        //! function that manages the unimaging
                        [B]"!!!!!"[/B]
                        bool CBasisSplineImager1d::convertSourceToCorrelation( const CSourceFtnBase& souin, CCorrFtn1dHisto& corrout, const parameterMap& m ){
                         
                            return CBasisFuncImager1d::convertSourceToCorrelation( souin, corrout, m );
                        }
                         
                        //--------------------- imageit ---------------------------
                        //! Code to image a 1d source, with equality constraints
                        double CBasisSplineImager1d::imageit(CBasisFunctionExpansion1d& souout){
                         
                            CBasisSpline1d* souPtr = dynamic_cast<CBasisSpline1d*>(&souout);
                            if (souPtr==NULL) throw MESSAGE<<"Source argument must derive from CBasisSpline1d"<<ENDM_FATAL;
                         
                            // Image using the generic code or optimize knots
                            double chi2 = CBasisFuncImager1d::imageit( *souPtr );
                         
                            // Compute final summed relative error of source (to emulate old "optimal knot" behavior)
                            double relerr=0.0;
                            for (int i=0;i<souout.ndata;++i){relerr+=abs(souout.data[i]/sqrt(souout.covmtx[i][i]));}
                            
                            // Compute the "figure of merit" that we'll minimize when doing the optimal knots
                            return chi2 + optimize_knots_minimizer_func_weight * relerr;
                        }
                         
                        //-------------------- do_optimal_knots ----------------------------
                        double CBasisSplineImager1d::do_optimal_knots(CBasisSpline1d& souout){
                        #ifdef __USE_GSL__
                         
                            // don't have to set souWork because we already ran imageit once
                            // souWork.CopyState(souout);
                         
                            /* variable declarations */
                            cout << "  Performing knot optimization"<<endl;
                            size_t nVarKnots = ndata_sou-(spline_degree+1);
                            const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
                            gsl_multimin_fminimizer *s = NULL;
                            gsl_vector *ss, *x;
                            gsl_multimin_function minex_func;
                            size_t iter = 1, i;  // we already ran imageit once, so set iter to 1
                            int status;
                            double size;
                         
                            /* Initial vertex size vector */
                            ss = gsl_vector_alloc (nVarKnots);
                         
                            /* Set all step sizes to ?? */
                            double dxKnots=(rmax)/(nVarKnots+1);
                            gsl_vector_set_all (ss, 0.75*dxKnots);
                         
                            /* Starting point */
                            x = gsl_vector_alloc (nVarKnots);
                            for (unsigned int i=0;i<nVarKnots;++i) gsl_vector_set(x, i, souout.knots[i+spline_degree+1]);
                            cout << "    Variable knots initialized"<<endl;
                         
                            /* Initialize method */
                            minex_func.f = &static_imageit;
                            minex_func.n = nVarKnots;
                            minex_func.params = (void *)this;
                            s = gsl_multimin_fminimizer_alloc (T, nVarKnots);
                            gsl_multimin_fminimizer_set (s, &minex_func, x, ss);
                            cout << "    Simplex minimizer initialized"<<endl;
                         
                            /* Iterate */
                            do {
                                iter++;
                                status = gsl_multimin_fminimizer_iterate(s);
                              
                                if (status) break;
                         
                                size = gsl_multimin_fminimizer_size (s);
                                status = gsl_multimin_test_size (size, 1e-2);
                         
                                if (status == GSL_SUCCESS) printf ("converged to minimum atn");
                         
                                printf ("%5d ", int(iter));
                                for (i = 0; i < nVarKnots; i++) printf ("%12.5e ", gsl_vector_get (s->x, i));
                                
                                printf ("f() = %7.3f size = %.3fn", s->fval, size);
                            } while (status == GSL_CONTINUE && iter < 200);
                            
                            gsl_vector_free(x);
                            gsl_vector_free(ss);
                            gsl_multimin_fminimizer_free (s);
                         
                            souout.CopyState(souWork);
                            return (double)(status);
                         
                        #else
                         
                            return imageit(souout);
                         
                        #endif
                        }
                         
                        //-------------------- static_imageit ----------------------------
                        //! Wrapper to imageit that we can use to do optimization
                        //! using GSL.  Also, recomputes losource's knots using
                        //! the variable knots in variableKnots, handed to this
                        //! routine by the gsl minimizer
                        double CBasisSplineImager1d::static_imageit(const gsl_vector *variableKnots, void* classPtr){
                         
                        #ifdef __USE_GSL__
                            CBasisSplineImager1d *cls = (CBasisSplineImager1d*)classPtr;
                         
                            // compute number of knots we can vary.  if this doesn't match the 
                            // dimensions of variableKnots, we are screwed
                            int nVarKnots=cls->ndata_sou-(cls->spline_degree+1);
                         
                            // set the knots 
                            vector<double> myKnots(cls->ndata_sou+cls->spline_degree+1);
                            for (int i=0;i<cls->spline_degree+1;++i) {
                                myKnots[i]=cls->rmin;
                                myKnots[cls->ndata_sou+cls->spline_degree-i]=cls->rmax;
                            }
                            for (int i=0;i<nVarKnots;++i) {
                                while( (myKnots[cls->spline_degree+1+i]>cls->rmax) || (myKnots[cls->spline_degree+1+i]<cls->rmin) ) {
                                    myKnots[cls->spline_degree+1+i] =
                                        mod( abs(gsl_vector_get(variableKnots,i)), cls->rmax-cls->rmin ) + cls->rmin;
                                }
                            }
                            sort(myKnots.begin(),myKnots.end());
                            
                            // Redimension souWork to accomodate the new knots
                            cls->souWork.setDim( myKnots.size() - cls->souWork.spline_degree - 1 );
                         
                            // Now put in the new knots
                            cls->souWork.knots = stl2tntVec(myKnots);
                         
                            // re-build the Kmtx
                            parameterMap dummyMap;
                            cls->set_kmtx(cls->corrwork,cls->souWork,dummyMap);
                            
                            // Now image the source.  
                            return cls->imageit(cls->souWork); 
                         
                        #else
                         
                            return 0.;
                         
                        #endif
                         
                        }
                         
                        //------------------ set_knots --------------------------
                        //! master knot initializer routine
                        void CBasisSplineImager1d::set_knots(CBasisSpline1d& souout){
                         
                            // figure out if we have to use the default scheme instead of alternate
                            if (knot_init_scheme=="sampling_thm") {
                                if (spline_degree == 0){
                                    MESSAGE << "Requesting Spline degree = 0, so using default knotsn" <<ENDM_WARN;
                                    knot_init_scheme="default";
                                    ndata_sou=std::max(std::min(ndata_corr,ndata_sou),spline_degree+1);
                                } 
                                else if (kernel_particle1!=kernel_particle2){
                                    MESSAGE << "Sampling theorem doen't work on unlike pairs" <<ENDM_WARN;
                                    knot_init_scheme="default";
                                } 
                            }
                         
                            // these two make knots directly
                            if (knot_init_scheme=="default") 
                                set_knots_default(souout);
                            else if (knot_init_scheme=="user_defined_knots") 
                                set_knots_user_defined(souout);
                            // these two make collocation points which must be converted to knots
                            else if (knot_init_scheme=="sampling_thm") {
                                set_colloc_sampling_thm();
                                set_knots_from_colloc_points(souout);
                            }
                            else if (knot_init_scheme=="user_defined_collocation_points") 
                                set_knots_from_colloc_points(souout);
                            // default to this one
                            else 
                                set_knots_default(souout);
                        }
                         
                        //------------------- set_knots_default -------------------------
                        void CBasisSplineImager1d::set_knots_default( CBasisSpline1d& souout ){
                         
                            cout << "  Default source knot initializationn";
                            // make a temp spline w/ correct dimensions, copy temp bspline into working source
                            ndata_sou=std::min(static_cast<int>(ndata_corr/1.5),souout.ndata); //override if ndata_out unreasonable
                            if (ndata_sou != souout.ndata){
                                MESSAGE << "Number of coefficients requested is too big, lowering to "<<ndata_sou<<ENDM_WARN;
                                souout.setDim( ndata_sou );
                            }
                            rmin = souout.xmin;
                            rmax = souout.xmax;
                            souout.setDefaultKnots();
                        }
                         
                        //------------------- set_colloc_sampling_thm -------------------------
                        void CBasisSplineImager1d::set_colloc_sampling_thm( void ){
                         
                            static int maxnumzeros=40;
                         
                            cout << "   Using Sampling theorem to guess collocation pointsn";
                            cout << "       Getting zeroes from kerneln";
                            
                            // get true zeros of wavefunction for collocation points
                            vector<double> zeros(get_zeros(qscale,maxnumzeros,l));
                         
                            // make temp list ot r collocation points
                            vector<double> tmp_rcolloc(1,rmin);
                         
                            // prune list of zeros to get only collocation points w/ r < _rmax
                            for (int i=0;i<static_cast<int>(zeros.size());i++) {
                                if ((zeros[i]<rmax)&&(zeros[i]>rmin)) tmp_rcolloc.push_back(zeros[i]);
                            }
                         
                            // add last element
                            tmp_rcolloc.push_back(rmax);
                         
                            // make sure list sorted
                            sort(tmp_rcolloc.begin(),tmp_rcolloc.end());
                         
                            // save the collocation points
                            colloc_pts = tmp_rcolloc;
                        }
                         
                        //------------------- set_knots_from_colloc_points -------------------------
                        void CBasisSplineImager1d::set_knots_from_colloc_points( CBasisSpline1d& souout ){
                         
                            cout << endl;
                            cout << "    Converting collocation points into knotsn";
                            cout << "    Pre-thin collocation points:n";
                            for (int i=0;i<static_cast<int>(colloc_pts.size());++i){
                                cout <<"        "<< i << " " << colloc_pts[i]<<endl;
                            }
                         
                            // thin tmp_rcolloc
                            vector<double> rcolloc(1,colloc_pts[0]);
                            int nave=1;
                            for (int i=1;i<static_cast<int>(colloc_pts.size());++i) {
                                if (abs(colloc_pts[i]-rcolloc.back())<knot_tolerance) {
                                    rcolloc.back() = (nave/(nave+1))*(rcolloc.back()+colloc_pts[i]/nave);           
                                    nave++;
                                } else {
                                    rcolloc.push_back(colloc_pts[i]);
                                    nave=1;
                                }
                            }
                            cout << "    Post-thin collocation points:n";
                            for (int i=0;i<static_cast<int>(rcolloc.size());i++){
                                cout << "        "<<i << " " << rcolloc[i]<<endl;
                            }
                            
                            // create a temp bspline and set the optimal knots using the collocation points above
                            souout.setOptimalKnots(stl2tntVec(rcolloc));
                            // Since bspline knot setup may override the number of coefficients 
                            // (we may have asked for unreasonable number), we need to reset ndata_out
                            ndata_sou = souout.ndata;
                        }
                         
                        //------------------- set_knots_user_defined -------------------------
                        void CBasisSplineImager1d::set_knots_user_defined( CBasisSpline1d& souout ){
                         
                            // copy temp bspline into working source
                            souout.setDim(user_knots.size()-souout.spline_degree-1);
                            // set the knots 
                            souout.knots = stl2tntVec(user_knots);
                            // Since bspline knot setup may override the number of coefficients 
                            // (the user may have botched to knots/coeffs count), 
                            // we need to reset ndata_out
                            ndata_sou = souout.ndata;
                        }
                         
                        //------------------- set_no_data -------------------------
                        [B]"!!!!!"[/B]
                        void CBasisSplineImager1d::set_no_data( CSourceFtnBase& souout ){
                         
                            CBasisFuncImager1d::set_no_data( souout );
                            CBasisSpline1d* souPtr = dynamic_cast<CBasisSpline1d*>(&souout);
                            if (souPtr==NULL) throw MESSAGE<<"Source argument must derive from CBasisSpline1d"<<ENDM_FATAL;
                            souPtr->setDefaultKnots(); // will give 0 everywhere outside this range anyway
                        }
                         
                        //------------------- initialize_source -------------------------
                        [B]"!!!!!"[/B]
                        void CBasisSplineImager1d::initialize_source( const CCorrFtn1dHisto& corrin, CSourceFtnBase& souout, const parameterMap& m ){
                         
                            CBasisFuncImager1d::initialize_source(corrin,souout,m);
                            CBasisSpline1d* souPtr = dynamic_cast<CBasisSpline1d*>(&souout);
                            if (souPtr==NULL) throw MESSAGE<<"Source argument must derive from CBasisSpline1d"<<ENDM_FATAL;
                            souPtr->Read(m);
                            spline_degree=souPtr->spline_degree;
                            set_knots(*souPtr);
                        }
                         
                        //----------------- get_zeros ---------------------------
                        //!  Get list of first nZeros zeros for l<=lmax=rmax*q/hbarc
                        vector< double > CBasisSplineImager1d::get_zeros(double q, int nZeros, int l, double eps){
                         
                            vector<double> zeros;
                            
                            // if I did this right, this should be smaller than the spacing between any zeros
                            double xstep=0.5/(2.0*q/HBARC);  
                            
                            double xmin = eps;
                            double testlo;
                            double testhi;
                            
                            zero_struct azero;
                            
                            while (static_cast<int>(zeros.size())<nZeros){
                                testlo  = kernelPtr->GetValue(l,q,xmin); 
                                testhi  = kernelPtr->GetValue(l,q,xmin+xstep);
                         
                                // Make sure lower point isn't a zero
                                if ( abs(testlo) <= eps ) { 
                                    zeros.push_back(xmin);
                                    xmin+=xstep/2.0;
                                    
                                } else {
                         
                                    // Make sure upper point isn't a zero
                                    if ( abs(testhi) <= eps ) { 
                                        testlo  = kernelPtr->GetValue(l,q,xmin);
                                        testhi  = kernelPtr->GetValue(l,q,xmin+xstep/2.0);
                                    }
                         
                                    // OK, now look for zeros on the current interval
                                    if ( testlo*testhi <= 0.) {
                                        azero=find_zero(xmin,xmin+xstep,q,l,eps);
                                        if (azero.iszero) zeros.push_back(azero.result);
                                    }
                                }
                                
                                // ready for next step just past this zero
                                xmin+=xstep;
                            }
                            return zeros;
                        }
                         
                        //------------------- find_zero ------------------------
                        //!  Gets first zero between xmin & xmax, 
                        //!  starting at xmin.  l and q are fixed. 
                        zero_struct CBasisSplineImager1d::find_zero(double xmin, double xmax, double q, int l, double eps){
                            int nsteps=10;
                            double stepsize=(xmax-xmin)/nsteps,xleft,xright;
                            zero_struct ans;
                            for (int i=0;i<nsteps;++i){
                                xleft=xmin+i*stepsize;
                                xright=xleft+stepsize;
                                if (kernelPtr->GetValue(l,q,xleft)*kernelPtr->GetValue(l,q,xright)<=0.){ // is sign change
                                    if (abs(xleft-xright)<eps) {
                                        ans.iszero = true;
                                        ans.result = (xleft+xright)/2.;
                                        return ans;
                                    }
                                    else return find_zero(xleft,xright,q,l,eps);
                                }
                            }
                            
                            // never get here, unless is no zero
                            ans.result=rmax; 
                            ans.iszero=false; 
                            return ans; 
                        }
                        • Forum
                        • Beginners
                        • Don’t know what I’m doing wrong

                        Don’t know what I’m doing wrong

                        I am prompted to make a class named «secretType» in which it must include private variables: name of type string, height of type double and age and height of type int. I must also include public member functions:
                        print — outputs the data stored in the member variables with the appropriate titles

                        setName — function to set the name

                        setAge — function to set the age

                        setWeight — function to set the weight

                        setHeight — function to set the height

                        getName — value-returning function to return the name

                        getAge — value-returning function to return the age

                        getWeight — value-returning function to return the weight

                        getHeight — value-returning function to return the height

                        and a constructor with default parameters.

                        It seems to me like I have done everything properly, but I get countless errors when compiling stating that the prototypes and candidates are not the same, for example:
                        «[Error] prototype for ‘void secretType::setHeight(int)’ does not match any in the class ‘secretType’.»
                        «[Error] candidate is: void secretType::setHeight(double)»

                        Yet I didn’t declare setHeight as an int, I clearly declared it as a double

                         
                        void setHeight(double height);

                        I don’t know what I’m doing wrong. Any help would be appreciated.

                        1
                        2
                        3
                        4
                        5
                        6
                        7
                        8
                        9
                        10
                        11
                        12
                        13
                        14
                        15
                        16
                        17
                        18
                        19
                        20
                        21
                        22
                        23
                        24
                        25
                        26
                        27
                        28
                        29
                        30
                        31
                        32
                        33
                        34
                        35
                        36
                        37
                        38
                        39
                        40
                        41
                        42
                        43
                        44
                        45
                        46
                        47
                        48
                        49
                        50
                        51
                        52
                        53
                        54
                        55
                        56
                        57
                        58
                        59
                        60
                        61
                        62
                        63
                        64
                        65
                        66
                        67
                        68
                        69
                        70
                        71
                        72
                        73
                        74
                        75
                        76
                        77
                        78
                        79
                        80
                        81
                        82
                        83
                        84
                        85
                        86
                        87
                        88
                        89
                        90
                        91
                        92
                        93
                        94
                        95
                        96
                        97
                        98
                        99
                        100
                        101
                        #include <iostream>
                        #include <string>
                        
                        using namespace std;
                        
                        class secretType {
                        	
                        	public:
                        		
                        		// Constructor including parameters
                        		secretType(string = " ", int = 0, int = 0, double = 0);
                        		void print() const; // Prints for testing
                        		void setName(string name);
                        		void setAge(int age);
                        		void setWeight(int weight);
                        		void setHeight(double height);
                        		string getName()const;
                        		int getAge()const;
                        		int getWeight()const;
                        		double getHeight()const;
                        		
                        	private:
                        		
                        		string name;
                        		int age, weight;
                        		double height;
                        	
                        };
                        
                        // Creates member function definitions
                        void secretType::print() const {
                        	
                        	cout << "Name: " << name << endl;
                        	cout << "Age: " << age << endl;
                        	cout << "Weight: " << weight << endl;
                        	cout << "Height: " << height << endl;
                        	
                        }
                        
                        void secretType::setAge(int a) {
                        	
                        	age = a;
                        	
                        }
                        
                        void secretType::setName(string n) {
                        	
                        	name = n;
                        	
                        }
                        
                        void secretType::setWeight(int w) {
                        	
                        	weight = w;
                        	
                        }
                        
                        void secretType::setHeight(int h) {
                        	
                        	height = h;
                        	
                        }
                        
                        void secretType::getName()const {
                        	
                        	return name;
                        	
                        }
                        
                        void secretType::getAge()const {
                        	
                        	return age;
                        	
                        }
                        
                        void secretType::getWeight()const {
                        	
                        	return weight;
                        	
                        }
                        
                        void secretType::getHeight()const {
                        	
                        	return height;
                        	
                        }
                        
                        // Main program to test
                        int main() {
                        	
                        	secretType secretObject; // Creates an object to test
                        	secretObject.setName("Margaret Smith");
                        	secretObject.setAge(34);
                        	secretObject.setWeight(156);
                        	secretObject.setHeight(62);
                        	secretObject.print();
                        	
                        	system("PAUSE");
                        	return 0;
                        	
                        }

                        1
                        2
                        3
                        void secretType::setHeight(int h) {   // that's not a double!
                        	height = h;
                        }

                        Last edited on

                        Thank you tpb, I overlooked that, but it’s still giving me me errors. Here’s all of them (it’s a lot):

                        1
                        2
                        3
                        4
                        5
                        6
                        7
                        8
                        [Error] prototype for 'void secretType::getName() const' does not match any in class 'secretType'
                        [Error] candidate is: std::string secretType::getName() const
                        [Error] prototype for 'void secretType::getAge() const' does not match any in class 'secretType'
                        [Error] candidate is: int secretType::getAge() const
                        [Error] prototype for 'void secretType::getWeight() const' does not match any in class 'secretType'
                        [Error] candidate is: int secretType::getWeight() const
                        [Error] prototype for 'void secretType::getHeight() const' does not match any in class 'secretType'
                        [Error] candidate is: double secretType::getHeight() const

                        I’ll look over everything again.

                        Last edited on

                        They need to match exactly, including the const at the end and the return types.

                        Last edited on

                        Topic archived. No new replies allowed.

                        Понравилась статья? Поделить с друзьями:
                      • Error protocol swift
                      • Error protocol security negotiation or connection failure
                      • Error reading jobject from jsonreader path line 1 position 55
                      • Error protocol https not implemented tardsplaya
                      • Error protocol handshake failed