[C++] char * & a = char * b 이런 문법이 있나요?

lbm200의 이미지

다른게 아니라 템플릿 클래스부분을 보고 있는데

실제 매개변수와 형식 매개변수 데이터 형이 다른데 프로그램 실행에 이상이 없습니다. 예를들어,

아래처럼, 사용자 정의 템플릿 클래스 Stack을 선언해 줍니다.

Stack<const char *> st;

그리고 프로그램 중간에서 st의 멤버 함수 push를 호출하면서 const char * 를 전달합니다.

st.push( const char * s);

push의 함수 머리는 다음과 같습니다.

template <typename Type>
bool Stack<Type>::push(const Type & item) {... }

그러면, Type부분이 const char *로 변경되어야 하니까 push 함수 머리는 다음과 같이 변경 되어야 합니다.

bool Stack<const char *>::push(const const char * & item) {... }

결국 push 를 호출할때 실제 매개변수가 형식 매개변수로 대입되는 상황은 아래와 같아야 합니다.

const const char * & item = const char * s

도대체 이게 무슨 문법인지 모르겠습니다. 원래 C++ 에 이런 문법이 있나요??

익명_사용자의 이미지

다음의 코드를 이해하신다면, 이해가갈것입니다.

#include <cstdlib>                                                             
#include <cstring>                                                             
#include <cstdio>                                                              
 
void strdup_with_reference(const char* in, char*& out) {                       
    size_t len = 0;                                                            
 
    if (in) {                                                                  
        len = strlen(in);                                                      
        out = new char[len];                                                   
    }                                                                          
 
    for(size_t i=0; i<len; i++) {                                              
        out[i] = in[i];                                                        
    }                                                                          
}                                                                              
 
void strdup_with_double_pointer(const char* in, char** out) {                  
    size_t len = 0;                                                            
 
    if (in) {                                                                  
        len = strlen(in);                                                      
        *out = new char[len];                                                  
    }                                                                          
 
    for(size_t i=0; i<len; i++) {                                              
        (*out)[i] = in[i];                                                     
    }                                                                          
}                                                                              
 
int main(int argc, char* argv[]) {                                             
    const char* in = "STRING";                                                 
    char* out1 = NULL;                                                         
    char* out2 = NULL;                                                         
 
    strdup_with_reference(in, out1);                                           
    strdup_with_double_pointer(in, &out2);                                     
 
    printf("%s\n", out1);                                                      
    printf("%s\n", out2);                                                      
 
    return EXIT_SUCCESS;                                                       
}

lbm200의 이미지

포인터 참조에 대한 이해가 되었습니다.
포인터 참조로 받을때의 코드 작성 편의성에 대해서 말씀하신걸로 이해 됩니다.
아직 많이 부족하다는 걸 느꼈습니다. 감사힙니다.!!

dkim의 이미지

const 타입 한정자는 한정하는 타입이 타입 지정자의 맨 앞에 오는 타입일 경우, 그 한정하는 타입 앞에 놓을 수도 뒤에 놓을 수도 있습니다. 둘 다 올바른 표현이며 동일하게 취급합니다. 예를 들어, const char *char const * 둘 다 올바른 문법이며 동일한 타입을 표현합니다: pointer to const char.

앞에 놓는 형태가 좀 더 관용적이지만, 템플릿의 복잡한 타입을 이해하려할 때는 뒤에 놓는 형태가 쉬울 수 있습니다. 보여주신 선언들을 뒤에 놓는 형태로 표현하면 다음과 같습니다:

template <typename Type>
bool Stack<Type>::push(Type const & item);
 
Stack<char const *> st;

따라서, 템플릿 패라미터 Typechar const *로 대체하면 다음처럼 됩니다:

bool Stack<char const *>::push(char const * const & item);

char const * const &는 reference to const pointer to const char 형을 의미합니다. 따라서, push() 함수에는 char const * (pointer to const char)와 char const * const (const pointer to const char) 형의 인자를 넘겨줄 수 있습니다.

lbm200의 이미지

참고하는 서적이 입문서이고, 그 부분에 이르기까지 어떠한 관련문법도 언급하지 않아서 좀 당황스럽습니다.

말씀하신 부분의 설명이 없어서 이해가 안 되었습니다.

많이 부족함을 느낍니다.

가르쳐 주셔서 감사합니다!

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.