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

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C3867

Compiler Error C3867

11/04/2016

C3867

C3867

bc5de03f-e01a-4407-88c3-2c63f0016a1e

Compiler Error C3867

‘func’: function call missing argument list; use ‘&func’ to create a pointer to member

You tried to take the address of a member function without qualifying the member function with its class name and the address-of operator.

This error can also be generated as a result of compiler conformance work that was done for Visual Studio 2005: enhanced pointer-to-member conformance. Code that compiled prior to Visual Studio 2005 will now generate C3867.

Examples

C3867 can be issued from the compiler with a misleading suggested resolution. Whenever possible, use the most derived class.

The following sample generates C3867 and shows how to fix it.

// C3867_1.cpp
// compile with: /c
struct Base {
protected:
   void Test() {}
};

class Derived : public Base {
   virtual void Bar();
};

void Derived::Bar() {
   void (Base::*p1)() = Test;   // C3867
   &Derived::Test;   // OK
}

The following sample generates C3867 and shows how to fix it.

// C3867_2.cpp
#include<stdio.h>

struct S {
   char *func() {
      return "message";
   }
};

class X {
public:
   void f() {}
};

int main() {
   X::f;   // C3867

   // OK
   X * myX = new X;
   myX->f();

   S s;
   printf_s("test %s", s.func);   // C3867
   printf_s("test %s", s.func());   // OK
}

The following sample generates C3867 and shows how to fix it.

// C3867_3.cpp
class X {
public:
   void mf(){}
};

int main() {
   void (X::*pmf)() = X::mf;   // C3867

   // try the following line instead
   void (X::*pmf2)() = &X::mf;
}

The following sample generates C3867.

// C3867_4.cpp
// compile with: /c
class A {
public:
   void f(int) {}

   typedef void (A::*TAmtd)(int);

   struct B {
      TAmtd p;
   };

   void g() {
      B b1;
      b1.p = f;   // C3867
   }
};

The following sample generates C3867.

// C3867_5.cpp
// compile with: /EHsc
#include <iostream>

class Testpm {
public:
   void m_func1() {
      std::cout << m_num << "tm_func1n";
    }

   int m_num;
   typedef void (Testpm::*pmfn1)();
   void func(Testpm* p);
};

void Testpm::func(Testpm* p) {
   pmfn1 s = m_func1;   // C3867
   pmfn1 s2 = &Testpm::m_func1;   // OK
   (p->*s2)();
}

int main() {
   Testpm *pTestpm = new Testpm;
   pTestpm->m_num = 10;

   pTestpm->func(pTestpm);
}

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. Показов 5386. Ответов 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 ,
I am was trying to develop a multi threaded application.

The thread function  calls other functions.I want to thread a  function multiple times but each function has its own parameters.

I have posted the jest of the code

Say the
.h file
Class example
{
UINT mythread(LPVOID arg);
void funcA();
void funcB();
};
.cc file
UINT example::FileMonThread(LPVOID arg);
{
Cstring a=reinterpret_cast<CString*>(arg);

//Call funcA
funcA();

//call functionB
funcB()
}

void test::funcA()
{
………….
………..

}
void test::funcB()
{
…………..
………….

}
In my main I have
/////////////////////////////////////////////////////////////////////////////////////////
example test[3];
csarray par;
..
..
//here I add parameters into the array

for(int i=0;i<3;i++)
{

AfxBeginThread(testIdea.mythread,(LPVOID)&par.getat(i));

}

….
….
…..

for(int i=0;i<3;i++)
    {
        if(TerminateThread(testIdea.mythread, 0) == FALSE)
        {
            // Could not force thread to exit -> call ‘GetLastError()’
            //Got to handle the the error
            THROW_WIN32(«unable to stop the threads»);
        }

           }

////////////////////////////////////////////////////////////////////////////////////

While compiling I am getting the error
error C3867:function call missing argument list use ‘&example::mythread’ to create a pointer to member

Cheers,
Pat

I’m trying to compile a code in Visual Studio, but I keep getting the following error:

Error 4 error C3867: ‘MindSet::Form1::handleDataValueFunc’: function call missing argument list; use ‘&MindSet::Form1::handleDataValueFunc’ to create a pointer to member c:documents and settingslicapdesktopmindsetmindsetmindsetForm1.h 122 1 MindSet

This is my code

#pragma endregion
void handleDataValueFunc(unsigned char extendedCodeLevel, unsigned char code,
    unsigned char valueLength, const unsigned char *value, void *customData)
{
    FILE *arq1;
    FILE *arq2;
    FILE *arq3;
        arq1 = fopen("raw.txt","a");
        arq2 = fopen("atencao.txt","a");
        arq3 = fopen("meditacao.txt","a");

    if (extendedCodeLevel == 0 && code == RAW_WAVE_CODE)
    {
        short rawValue = ((value[0] << 8) & 0xff00) | (0x00ff & value[1]);
        printf("%dn", rawValue);
        fprintf(arq1,"%dn",rawValue);
    }
    if (extendedCodeLevel == 0 && code == ATTENTION_LEVEL_CODE)
        {
            short attentionValue = (value[0] & 0xFF);
            printf("%dn", attentionValue);
            fprintf(arq2,"%dn",attentionValue);
        }
    if (extendedCodeLevel == 0 && code == MEDITATION_LEVEL_CODE)
        {
            short meditationValue = (value[0] & 0xFF);
            printf("%dn", meditationValue);
            fprintf(arq3,"%dn",meditationValue);
        }
    fclose(arq1);
    fclose(arq2);
    fclose(arq3);
}
private: System::Void IniciarCaptura_Click(System::Object^  sender, System::EventArgs^  e) {

    SerialPort* port = new SerialPortW32();

    if (port->open())
    {
        /* Initialize ThinkGear stream parser */
        ThinkGearStreamParser parser;
        THINKGEAR_initParser(&parser, PARSER_TYPE_PACKETS, handleDataValueFunc, NULL);

        unsigned char byteRead;
        for (int i = 0; i < 100000; i++)
        {
            if (port->read(&byteRead, 1) == 1)
            {
                THINKGEAR_parseByte(&parser, byteRead);
                fflush(stdout);
            }
            else
            {
                //cerr << "Erro na leitura da porta" << endl;
                break;
            }
        }

        port->close();
    }
    else
    {
        //cout << port->getErrorMessage() << endl;
    }
    delete port;
    //return 0;
    }
};

}

I’ve already tried to add a «&» before «handleDataValueFunc», but it only returns another error message. Can anybody help?

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.

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора c3861
  • Ошибка компиляции для платы digispark
  • Ошибка компилятора c3699
  • Ошибка компиляции для платы arduino uno что делать
  • Ошибка компилятора c3646