강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

yahoo님의 프로필 이미지
yahoo

작성한 질문수

홍정모의 따라하며 배우는 C++

10.3 집합 관계

6:36 `void registerStudent(const Student & const student_input)`error

작성

·

347

1

안녕하세요, const를 두번 넣으니까 아래와 같은 에러가 나옵니다. 이렇게 바꾸면 문제가 없습니다. const Student & student_input
const가 2개 필요한 이유가 따로 있을까요?

/usr/bin/clang++ -std=c++17 -fcolor-diagnostics -fansi-escape-codes -g /Users/user/Documents/cpp/10-3/10-3.cpp -o /Users/user/Documents/cpp/10-3/10-3
In file included from /Users/user/Documents/cpp/10-3/10-3.cpp:4:
/Users/user/Documents/cpp/10-3/Lecture.h:26:40: error: 'const' qualifier may not be applied to a reference
    void assignTeacher(const Teacher & const teacher_input)
                                       ^
/Users/user/Documents/cpp/10-3/Lecture.h:31:42: error: 'const' qualifier may not be applied to a reference
    void registerStudent(const Student & const student_input)

code

# Lecture.h
#pragma once

#include <vector>
#include "Student.h"
#include "Teacher.h"

class Lecture
{
private:
    std::string m_name;

    Teacher teacher;
    std::vector<Student> students;

public:
    Lecture(const std::string & name_in)
        : m_name(name_in)
    {}

    ~Lecture()
    {
        // do NOT delete teacher
        // do NOT delete students
    }

    void assignTeacher(const Teacher & const teacher_input)
    {
        teacher = teacher_input;
    }

    void registerStudent(const Student & const student_input)
    {
        students.push_back(student_input); // vector에 넣는다
    }

    void study()
    {
        std::cout << m_name << " Study " << std::endl << std::endl;

        for (auto & elem : students) // for each에서 ref로 받아야 값 변환 가능
            elem.setIntel(elem.getIntel() + 1);
    }

    friend std::ostream & operator << (std::ostream & out, const Lecture & lecture)
    {
        out << "Lecture name : " << lecture.m_name << std::endl;
        out << lecture.teacher << std::endl;

        for (auto elem : lecture.students)
            out << elem << std::endl;
        
        return out;
    }
};

답변 1

2

안녕하세요, 답변 도우미 Soobak 입니다.

C++ 언어에서 참조에 대해 const 키워드를 두 번 사용하는 것은 문법적으로 허용되지 않으며, 실제로 필요성이 없습니다.

질문해주신 const Student & const student_input 에서,

첫 번째 const참조되는 'Student 객체' 에 대해 적용됩니다.

두 번째 const참조 자체에 대해 상수성을 나타내려고 하지만, 참조는 이미 상수성을 가지고 있으므로 두 번째 const 는 의미가 없습니다.
(첨부해주신 에러의 내용도 이러한 오류를 지적하고 있습니다.
error: 'const' qualifier may not be applied to a reference void assignTeacher(const Teacher & const teacher_input))

참조는 '참조하는 객체' 에 대해 일종의 alias 로 동작하며, 한 번 초기화되면 다른 객체를 참조하도록 변경할 수 없습니다. 그렇기 때문에 참조를 const 로 선언하는 것이 의미가 없는 것입니다.

즉, "const가 2개 필요한 이유가 따로 있을까요?" 라고 질문주신 것에 대해서는 없습니다 라고 답변드리는 것이 적절한 것 같습니다.

yahoo님의 프로필 이미지
yahoo
질문자

감사합니다! 강의영상에는 2번 사용해도 돌아가던데 왜 돌아갔을까요...

안녕하세요, 답변 도우미 Soobak 입니다.

죄송합니다. 보다 정확하게 설명드리지 못했네요.

이유는 개별 컴파일러와 환경에 따라서 에러 검증의 수준이 다르기 때문입니다.
컴파일러와 환경에 따라서 에러를 출력할 수도, 그렇지 않을 수도 있습니다.
두 번째 const 의 필요성이 적은 것은 맞습니다.
만약, 에러를 출력하지 않는다면 두 번째 const 키워드는 컴파일러가 자동으로 무시하게 됩니다.

따라서, 환경 간의 차이 때문에 발생한 문제라고 생각하시는 것이 적절할 것 같습니다.

하지만 그 동안 선생님께서 강의에서 강조해주셨던 것 처럼, const 키워드는 프로그래머의 실수 방지에 아주 큰 도움이 되므로, const 키워드를 사용할 수 있는 경우에는 되도록 사용하는 것이 좋습니다.

위 내용들을 바탕으로, 상황과 환경에 맞게 선택하는 것이 좋은 것으로 이해하시는 것이 적절할 것 같습니다.

yahoo님의 프로필 이미지
yahoo

작성한 질문수

질문하기