Ошибка компилятора c3867

My code was working fine until I reloaded the program a few hours later. Now I get these this error:

error C3867: ‘player::getxPos’: function call missing argument list; use ‘&player::getxPos’ to create a pointer to member

error C3867: ‘player::getyPos’: function call missing argument list; use ‘&player::getyPos’ to create a pointer to member

This is the code in question:

if (P->shoot())
{
    shotVector.push_back(shot());
    eS = shotVector.size();
    shotVector[eS-1].initShot(
        P->getxPos, // C3867
        P->getyPos // C3867
    );
}

I’m trying to call two functions from a class called player and these two functions look like this:

int player::getxPos(){
    return xPos;
};

int player::getyPos(){
    return yPos;
};

What’s being done is that I’m trying to ask for the players position and then use that to decide where to shoot from.

My code was working fine until I reloaded the program a few hours later. Now I get these this error:

error C3867: ‘player::getxPos’: function call missing argument list; use ‘&player::getxPos’ to create a pointer to member

error C3867: ‘player::getyPos’: function call missing argument list; use ‘&player::getyPos’ to create a pointer to member

This is the code in question:

if (P->shoot())
{
    shotVector.push_back(shot());
    eS = shotVector.size();
    shotVector[eS-1].initShot(
        P->getxPos, // C3867
        P->getyPos // C3867
    );
}

I’m trying to call two functions from a class called player and these two functions look like this:

int player::getxPos(){
    return xPos;
};

int player::getyPos(){
    return yPos;
};

What’s being done is that I’m trying to ask for the players position and then use that to decide where to shoot from.

Alex Z

27 / 1 / 0

Регистрация: 29.06.2011

Сообщений: 136

1

16.01.2013, 07:25. Показов 5446. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Списал код из учебника. Наверное, там где-то опечатка, так как при компиляции возникает ошибка.

C++
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
#include <iostream>
using namespace std;
 
class Mammal
{
public:
    Mammal():itsAge(1) { }
    virtual ~Mammal()  { }
    virtual void Speak() const = 0;
    virtual void Move()  const = 0;
protected:
    int itsAge;
};
 
class Dog : public Mammal
{
public:
    void Speak() const { cout << "Woof!\n"; }
    void Move()  const { cout << "Walking to heel...\n"; }
};
 
class Cat : public Mammal
{
public:
    void Speak() const { cout << "Meow!\n"; }
    void Move()  const { cout << "Slinking...\n"; }
};
 
class Horse : public Mammal
{
public:
    void Speak() const { cout << "Whinny!\n"; }
    void Move()  const { cout << "Galloping...\n"; }
};
 
int main()
{
    void (Mammal::*pFunc)() const = 0;
    Mammal* ptr = 0;
    int Animal;
    int Method;
    bool fQuit = false;
 
    while (fQuit == false)
    {
        cout << "(0)Quit (1)dog (2)cat (3)horse: ";
        cin >> Animal;
        switch (Animal)
        {
        case 1:  ptr = new Dog;   break;
        case 2:  ptr = new Cat;   break;
        case 3:  ptr = new Horse; break;
        default: fQuit = true;    break;
        }
 
        if (fQuit == false)
        {
            cout << "(1)Speak (2)Move: ";
            cin >> Method;
            switch (Method)
            {
            case 1:  pFunc = Mammal::Speak; break;
            default: pFunc = Mammal::Move;  break;
            }
 
            (ptr->*pFunc)();
            delete ptr;
        }
    }
        
    char response;        
    std::cin >> response; 
 
    return 0;     
}

Компилятор пишет:

error C3867: Mammal::Speak: в вызове функции отсутствует список аргументов; используйте «&Mammal::Speak» для создания указателя на член

error C3867: Mammal::Move: в вызове функции отсутствует список аргументов; используйте «&Mammal::Move» для создания указателя на член

И отмечает ошибочными строчки 62 и 63. Объясните кто понимает, где тут ошибка. (Тема называется «Указатели на функции-члены»)



0



Schizorb

512 / 464 / 81

Регистрация: 07.04.2012

Сообщений: 869

Записей в блоге: 1

16.01.2013, 08:50

2

Нужны амперсанды для получения адреса:

C++
1
2
case 1:  pFunc = &Mammal::Speak; break;
default: pFunc = &Mammal::Move;  break;



2



v.a.l.i.d

424 / 389 / 113

Регистрация: 21.09.2012

Сообщений: 913

16.01.2013, 14:15

3

Цитата
Сообщение от Schizorb
Посмотреть сообщение

Нужны амперсанды для получения адреса:

А почему нужны амперсанды? Вроде я где то читал, чтобы получить адрес функции, то ее можно просто записать без круглых скобок

C++
1
2
3
4
5
6
7
8
9
10
11
12
void F()
{
 
}
 
int main()
{
    cout << F << endl;  // печатает адрес функции F()
 
    system("pause");
    return 0;
}



0



ArmanPrestige

Pied Piper

236 / 227 / 57

Регистрация: 15.01.2013

Сообщений: 855

16.01.2013, 14:21

4

Цитата
Сообщение от v.a.l.i.d
Посмотреть сообщение

А почему нужны амперсанды? Вроде я где то читал, чтобы получить адрес функции, то ее можно просто записать без круглых скобок

C++
1
2
3
4
5
6
7
8
9
10
11
12
void F()
{
 
}
 
int main()
{
    cout << F << endl;  // печатает адрес функции F()
 
    system("pause");
    return 0;
}

если попробуете int x = F то получите эррор.
сосздаем типа void* указатель и радуемся
void *x = F;



0



512 / 464 / 81

Регистрация: 07.04.2012

Сообщений: 869

Записей в блоге: 1

16.01.2013, 15:20

5

Цитата
Сообщение от v.a.l.i.d
Посмотреть сообщение

Вроде я где то читал, чтобы получить адрес функции, то ее можно просто записать без круглых скобок

Для обычных функций да, но тут у нас методы класса. Для них, как правило, нужно явно указывать, что необходим адрес. Хотя, некоторые компиляторы пропускают код и без амперсандов (тут прочитал)

Вообще, запись типа Mammal::Speak, видимо, расценивается как попытка обращения к нестатическому методу класса при отсутствии объекта, поэтому ошибка.



2



27 / 1 / 0

Регистрация: 29.06.2011

Сообщений: 136

16.01.2013, 18:37

 [ТС]

6

Цитата
Сообщение от Schizorb
Посмотреть сообщение

Вообще, запись типа Mammal::Speak, видимо, расценивается как попытка обращения к нестатическому методу класса при отсутствии объекта, поэтому ошибка.

Так а строчки 50, 51, 52 вроде как раз создают объект (в зависимости от введённого числа).

(или нет? …)



0



512 / 464 / 81

Регистрация: 07.04.2012

Сообщений: 869

Записей в блоге: 1

16.01.2013, 18:49

7

Цитата
Сообщение от Alex Z
Посмотреть сообщение

Так а строчки 50, 51, 52 вроде как раз создают объект

Да, но вот это обращение к методу — Mammal::Speak — происходит не через объект.

У вас, кстати в сообщении компилятора суть ошибки описана, и даже предложено решение проблемы.

Цитата
Сообщение от Alex Z
Посмотреть сообщение

Mammal::Speak: в вызове функции отсутствует список аргументов; используйте «&Mammal::Speak» для создания указателя на член



1



hi Guys when i’m trying to compile this code for some reason it wont refere to my class when i try and call it in main??

I am now totally lost with it so any help would be most appreciated

#include <iostream>
using namespace std;

class cteams
{
private:
static const char f_team1 , f_team2 , f_team3 ,f_team4 ;
int f_points_for_team1, f_points_for_team2, f_points_for_team3, f_points_for_team4;

public:
cteams (int startscore = 0);
int set_team1_score (int);
void set_team2_score (void);
void set_team3_score (void);
void set_team4_score (void);

};
cteams::cteams (int)
{

}

int cteams::set_team1_score (int startscore)
{
f_points_for_team1 = startscore;
}
void cteams::set_team2_score (void)
{
f_points_for_team2 = 0;
}
void cteams::set_team3_score (void)
{
f_points_for_team3 = 0;
}
void cteams::set_team4_score (void)
{
f_points_for_team4 = 0;
}

int main()
{
int start;
cteams score (start);
cout << «Hey team 1 score is » <<score.set_team1_score << endl;

system («pause»);
}

thanks in advance guys

Please use [code][/code] tags

in this line: cout << "Hey team 1 score is " <<score.set_team1_score << endl; you are using set_team1_score as a variable but it is a function

Hey Bazzy thanks for the help their. So I’m using it as a variable and not a function, I’m sure this will sound soo silly but How do i convert from a variable to a function then?

thanks so much for your help i have spent hours on this

ad parentheses and arguments:
score.set_team1_score ( /*the parameter you defined was: int startscore so give it a value*/ )

I gave it a value in the public class int startscore = 0 woudl i have to give it a value further down?

Once I put score.set_team1_score () it now says that int

cteams::set_team1_score (int startscore)
{
f_points_for_team1 = startscore;
}

must return a value??

It was declared as int set_team1_score (int); so it must return a value.
If you don’t want to return a value, use void as return type but if you do so, cout won’t display any value.
I think you want to return f_points_for_team1 after assigning it a new value

Last edited on

I have got totally lost with this now LOL. as you can probably guess im very new to coding!!

what are your views on a slightly different take on this

#include <iostream>
using namespace std;

class cteams
{
private:
static const char f_team1 [10], f_team2 [10], f_team3 [10],f_team4 [10];
int f_points_for_team1, f_points_for_team2, f_points_for_team3, f_points_for_team4;
public:
cteams (int);
int set_team1_score (){return (f_points_for_team1);}
int set_team2_score (){return (f_points_for_team2);}
int set_team3_score (){return (f_points_for_team3);}
int set_team4_score (){return (f_points_for_team4);}
};

cteams::cteams (int TheScore)
{
f_points_for_team1 = TheScore;
f_points_for_team2 = TheScore;
f_points_for_team3 = TheScore;
f_points_for_team4 = TheScore;
}

int main()
{
cteams team1 (0);
cteams team2 (0);
cteams team3 (0);
cteams team4 (0);

cout << «Team 1 Begins with » << team1.set_team1_score () << » Team 2 Begins with » << team2.set_team2_score () << endl;

system («pause»);
}

I think that should work but is that a propperly coded class with a constructor in? as im just never sure

I think you are messing a bit with setter and getter functions,
to have a good interface for your class the functions should be like these:

1
2
3
4
5
6
7
8
9
10
11
12
13
//Prototypes
void set_team1_score ( int );
int get_team1_score ();

//Bodies
void cteams::set_team1_score ( int newScore)
{
    f_points_for_team1 = newScore;
}
int cteams::get_team1_score ()
{
    return f_points_for_team1;
}

The constructor is fine, you can also have an initializer list on it:

1
2
3
4
5
cteams::cteams (int TheScore):
    f_points_for_team1 ( TheScore ), f_points_for_team2 ( TheScore )
    f_points_for_team3 ( TheScore ), f_points_for_team4 ( TheScore )
{
}

Notice that the prefix ‘f’ you used for names on the ungarian notation may mean ‘float’ or ‘flag’ but your variables are integers and C strings

How would you perhaps go about incorporating txt in to this class? as I want it to call a name for a team. and Bazzy your a diamond thanks buddy I have managed to finish the class to call back numbers now just need to sort the txt.

Any help most appreciated thanks guys

#include <string> and then you will be able of using std::string.
Create variables of that type and do what you need
eg:

1
2
3
4
5
string team1_name;

cteam ( const string &name ) : team1_name ( name )
{
}

As silly as this probably sounds, would you be able to elaborate alittle more on this? would I incorporate this in to my class? perhaps at the begining of the class? and write it in very much the same way as I have written the rest of the class? and thanks again Bazzy, it’s much appreciated this help

The thing is I want my program to ask the user to enter a team name, anything he wants to call a team, and then the program takes this data and stores it in the new class i have built and I can call upon it when ever i choose if you get me? I have managed to do that with the numbers just cant seem to get it to implement text. Thanks again

Just create string variables as you created the ints for scores.
To get input, do something like this:

1
2
3
4
5
cteam team1;
string input;
cout << "What name you want for team 1? ";
getline ( cin, input );
team1.set_name ( input );

Where set_name may be implemented like this:

1
2
3
4
void cteam::set_name( const string & newName )
{
    name = newName; // replace name with whatever symbol you used for the member to hold the string
}

Here is the code so far. I am assuming you mean create string variables like i did for the scores, would they be int? or something else? and Would I be laying out Set_Name like the same as I did for my set_team_scores etc?? just a tad confused still but I am getting their LOl thanks so much, My brain is on over drive with this

#include <iostream>
#include <string>
using namespace std;

class cteams
{
private:
char f_team1 [30], f_team2 [30], f_team3 [30],f_team4 [30];
int f_points_for_team1, f_points_for_team2, f_points_for_team3, f_points_for_team4;
public:
cteams (int);
void set_team1_score (int),set_team2_score (int),set_team3_score (int),set_team4_score (int);
int get_team1_score (),get_team2_score (),get_team3_score (),get_team4_score ();

};

void cteams::set_team1_score (int StartScore)
{
f_points_for_team1 = StartScore;
}
int cteams::get_team1_score()
{
return (f_points_for_team1);
}

I haven’t included all my code as don’t want to bore you but would i implement the string in to the class very much the same way as I have done here with the scores?

Yes, however, don’t use char …[##], just use string … like this:

string _team1, team2; //...

#include <iostream>
#include <string>
using namespace std;

class cteams
{
private:
string f_team1, f_team2, f_team3,f_team4;
int f_points_for_team1, f_points_for_team2, f_points_for_team3, f_points_for_team4;
public:
cteams (int);
void set_team1_score (int),set_team2_score (int),set_team3_score (int),set_team4_score (int);
int get_team1_score (),get_team2_score (),get_team3_score (),get_team4_score ();
void set_name (string);

};
void cteams::set_name (const string &newName)
{
string f_team1 = newName;
}

int main()
{

cteams teamscore (0);
cteams team1;
string input;
cout << «Enter a name here «;
getline (cin, input);
team1.set_name (input);
cout << «Team 1 Begins with » << teamscore.get_team1_score () << » Team 2 Begins with » << teamscore.get_team2_score () << endl;

system («pause»);
}

these are the 2 main chunks of my code, the problem im having here is it’s saying overload member function not found?? and no appropriate default constructor?? this is getting more and more confusing but I’m getting their with much appreciated help from you guys!!

Declaration and body arguments don’t match:

1
2
3
4
5
6
void set_name (string); // type: string

void cteams::set_name (const string &newName) // type: const string &
{
string f_team1 = newName;
}

Bazzy once again, I honestly cannot thank you enough!! It’s great to know their are people actually out there willing to help others!
I know I probably sound like a total noob but where others would point and laugh you actually help, Had bad experiences on other forums!!

I just want you to know it’s most appreciated!! So thank you.

Topic archived. No new replies allowed.

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка коммутации что это
  • Ошибка компилятора c3863
  • Ошибка ккт 70a2
  • Ошибка климат контроля se8701 11
  • Ошибка компилятора c3848

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: