c++ static을 쓰지 않는 함수포인터 질문입니다..

dionysos의 이미지

static 을쓰지 않고 c++에서 함수포인터를 사용할수 있는 방법은 없나요 검색을 해보니 친절하게 설명해 주신듯한데 실력이 부족해서인지 이해를 잘 못하겠군요

#include<iostream.h>

class AAA {
public:
	AAA();
	int (*ir_set[3])();
	int a();
	int b();
	int c();

};
AAA::AAA()
{
	ir_set[0] = AAA::a;
	ir_set[1] = AAA::b;
	ir_set[2] = AAA::c;

}

int AAA::a()
{
	return 0;
}
int AAA::b()
{
	return 0;
}
int AAA::c()
{
	return 0;
}

int main()
{
               return 0;
}

qt project\aa\aaa.cpp(14) : error C2440: '=' : cannot convert from 'int (__thiscall AAA::*)(void)' to 'int (__cdecl *)(void)'
        There is no context in which this conversion is possible
D:\qt project\aa\aaa.cpp(15) : error C2440: '=' : cannot convert from 'int (__thiscall AAA::*)(void)' to 'int (__cdecl *)(void)'
        There is no context in which this conversion is possible
D:\qt project\aa\aaa.cpp(16) : error C2440: '=' : cannot convert from 'int (__thiscall AAA::*)(void)' to 'int (__cdecl *)(void)'
        There is no context in which this conversion is possible

이런에러만 잔뜩 나오는군요
쓸수 있는 방법이 없을까요 부탁드립니다
happyjun의 이미지

오류문에 나온것 처럼 member function의 prototype은 int (*) () 가 아니라 int ( AAA::* ) () 입니다.

따라서 int (*ir_set[3])()int (AAA::*ir_set[3])() 로 바꾸시면 됩니다. 그리고 ir_set[0] = AAA::air_set[0] = &AAA::a 으로 바꾸셔야 합니다.

호출하는 방법은 member function은 __thiscall 이기 때문에 속해 있는 object instance가 필요합니다.

간단하게 예는 다음과 같습니다.

struct Test {
  void func() {}
};

void (Test:: *testFunc) () = &Test::func;

Test t;
(t.*(testFunc)) ();

즉 .* 연산자나 ->* 연산자를 이용해서 호출 해야 합니다.

따라서 원래 주어진 코드에서는 다음과 같이 호출해야 합니다.

AAA a;
(a.*(a.ir_set[0])) ();

----------------------------------------
http://moim.at
http://mkhq.co.kr

dionysos의 이미지

계속 안되서 이렇게 저렇게 바꿔서 해봤는데 잘안되서 물어봤는데 감사합니다..

c에서 되던게 c++에서 안되니.. 더 열심히 공부해야할듯 하네요

포인터 혹시 공부할 책같은거 있으면 추천해주세요.

노력은 배반하지 않는다.

happyjun의 이미지

외람되지만 member function pointer 같은 내용은 아직 C++에 대한 이해가 부족할 때는 필요없지 않을까 합니다.

일반적인 C++ 프로그램에서는 사용되지 않는 부분입니다. functor와 관련된 C++ library 제작시에나 필요할까 합니다.

C의 callback function 같은 것이 필요하시면 다형성이나 functor 또는 boost::function, boost::signal 같은 것으로 원하는 기능을 구현할 수 있습니다.

----------------------------------------
http://moim.at
http://mkhq.co.kr

tinywolf의 이미지

저는 자바의 인터페이스와 같은 형태로 가상 함수만 가진 클래스를 만들고 그걸 상속한 클래스 포인터를 콜백이 필요한 함수에게 알려주는 형태로 사용하길 좋아합니다. ^^

ㅡ_ㅡ;

r3d0ny0u의 이미지

java 든 c++ 이든 member function 은 객체(this) 를 참조함니다.
왜냐하면 객체를 생성후 member function 이 call 될때 변수들을 참조해야하기 때문입니다. 한 class 에서 생성된 여러개의 객체들이 서로다른 값의 변수들을 가지고 있고 그것에 대한 처리만 같은 function으로 하는 것입니다.

그러나 static function 은 그럴 필요가 없기 때문에 직접적으로 변수를 참조하지 못함니다. static member function 이라도 자신이 속한 class 에대한 변수를 직접 참조 못합니다.

girneter의 이미지

tinywolf wrote:
저는 자바의 인터페이스와 같은 형태로 가상 함수만 가진 클래스를 만들고 그걸 상속한 클래스 포인터를 콜백이 필요한 함수에게 알려주는 형태로 사용하길 좋아합니다. ^^

저는 C++ 초보라서 아는바가 없지만
좀 하시는 분의 code 를 보니
이런 식으로 하시더군요.
정석이 아닐까 싶네요

개념없는 초딩들은 좋은 말로 할때 DC나 웃대가서 놀아라. 응?

까막의 이미지

std::mem_fn, std::mem_fn_ref, boost::mem_fn 같은 것을 쓰시는게 좋을듯 싶네요. :)

C++에서는 함수포인터를 쓰기보다는, 저런 함수자(어댑터)를 사용하는 것이 훨씬 편하고 좋습니다. :)

일단 호출 가능한 모든 객체를 하나의 데이터타입으로 일관되게 처리할 수 있다는건 큰 장점이니까요. :)

boost::function 같은것을 참조하심이 좋을듯.

Crow's Maniacal World.
http://crowmania.cafe24.com

Let's be engineers!

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.