수다닷컴

  • 해외여행
    • 괌
    • 태국
    • 유럽
    • 일본
    • 필리핀
    • 미국
    • 중국
    • 기타여행
    • 싱가폴
  • 건강
    • 다이어트
    • 당뇨
    • 헬스
    • 건강음식
    • 건강기타
  • 컴퓨터
    • 프로그램 개발일반
    • C언어
    • 비주얼베이직
  • 결혼생활
    • 출산/육아
    • 결혼준비
    • 엄마이야기방
  • 일상생활
    • 면접
    • 취업
    • 진로선택
  • 교육
    • 교육일반
    • 아이교육
    • 토익
    • 해외연수
    • 영어
  • 취미생활
    • 음악
    • 자전거
    • 수영
    • 바이크
    • 축구
  • 기타
    • 강아지
    • 제주도여행
    • 국내여행
    • 기타일상
    • 애플
    • 휴대폰관련
  • 프로그램 개발일반
  • C언어
  • 비주얼베이직

c++ 템플릿 예제 질문

이퓨리한은지

2023.04.01



먼저 이 예제는 Animal의 무게를 나타내는 Animal class와 이 class를 가지고 배열을 만드는 Array class가 있습니다. main문에서 처음에 객체의 인스턴스를 생성하는 부분에서 생성자 함수가 어떻게 호출이 되는지 궁금해서 질문을 하고자 합니다.main문을 보시면
1. Arrayint theArray; // an array of integer 2. ArrayAnimal theZoo; // an array of Animals
이렇게 두가지가 있는데요. 객체를 생성하면 메모리가 할당되고 생성자 함수를 호출하게 됩니다. 첫번째 자료형이 int로 나타나 있을 때는 Array가 int로 템플릿화 되어있으니까
// implement the Constructor
template class T
ArrayT::Array(int size) :
itsSize(size)
{
pType = new T[size];
// the constructors of the type you are creating
}
위의 생성자 함수가 호출되어 size만큼 배열이 만들어 지는데요두번째 ArrayAnimal theZoo; 의 경우 에는 템플릿화 된 생성자 함수중에 copy constructor 외에는 호출이 될 수 있는 곳이없는 것 같습니다 그래서 첫번째 int 경우처럼 size만큼 배열을 만들 수 있는 곳이 copy constructor밖에 없는것 같은데요.복사 생성자(copy constructor)가 호출되는 경우는
1. 기존에 생성된 객체를 이용해서 새로운 객체를 초기화하는 경우2. call-by-value 방식의 함수호출 과정에서 객체를 인자로 전달하는 경우3. 객체를 반환하되 참조형으로 반환하지 않는 경우
이렇게 세가지가 있다고 합니다. 여기서 2번째 객체를 인자로 전달하는 경우가 근접한거 같은데이것때문에 ArrayAnimal theZoo;의 경우copy constructor가 호출이 되는게 맞을까요??
실제 호출이 되는지 보기위해 copy constructor에 std::cout 나는 theZoo; 구문을 넣어보았지만이 문장이 출력이 되지 않더라구요 ArrayAnimal theZoo;는 어떤 생성자를 호출하게 되는지 궁금합니다.
===================================================================================================================
#include iostreamconst int DefaultSize = 10;
//an array of Animal을 만들기 위해 Animal class를 선언class Animal
{
public:
Animal(int);
Animal();
~Animal() {}
int GetWeight() const { return itsWeight; }
void Display() const { std::cout itsWeight; }
private:
int itsWeight;
};Animal::Animal(int weight) :
itsWeight(weight)
{}Animal::Animal() :
itsWeight(0)
{}
template class T
class Array
{
public:
// constructors
Array(int itsSize = DefaultSize);
Array(const Array &rhs);
~Array() { delete[] pType; }// operators
Array& operator=(const Array&);
T& operator[](int offSet) { return pType[offSet]; }
const T& operator[](int offSet) const
{return pType[offSet];}
// accessors
int GetSize() const { return itsSize; }private:
T *pType;
int itsSize;
};// implementations follow...// implement the Constructor
template class T
ArrayT::Array(int size) :
itsSize(size)
{
pType = new T[size];
// the constructors of the type you are creating
// the constructors of the type you are creating
}// copy constructor
template class T
ArrayT::Array(const Array &rhs)
{
itsSize = rhs.GetSize();
pType = new T[itsSize];
for (int i = 0; iitsSize; i++)
pType[i] = rhs[i];
}// operator=
template class T
ArrayT& ArrayT::operator=(const Array &rhs)
{
if (this == &rhs)
return *this;
delete[] pType;
itsSize = rhs.GetSize();
pType = new T[itsSize];
for (int i = 0; iitsSize; i++)
pType[i] = rhs[i];
return *this;
}// driver program
int main()
{
Arrayint theArray; // an array of integers
ArrayAnimal theZoo; // an array of Animals
Animal *pAnimal;// fill the arrays
for (int i = 0; i theArray.GetSize(); i++)
{
theArray[i] = i * 2;
pAnimal = new Animal(i * 3);
theZoo[i] = *pAnimal;
delete pAnimal;
}
// print the contents of the arrays
for (int j = 0; j theArray.GetSize(); j++)
{
std::cout theArray[ j ]:\t;
std::cout theArray[j] \t\t;
std::cout theZoo[ j ]:\t;
theZoo[j].Display();
std::cout std::endl;
}return 0;
}

d

신청하기





COMMENT

댓글을 입력해주세요. 비속어와 욕설은 삼가해주세요.

번호 제 목 글쓴이 날짜
2701397 세로 100% 푸터부분이 바닥에 안붙어요(세로 100% 되는 소스를 썼거든요) 꽃겨울 2025-07-13
2701369 [긴급]로드해온 swf가 갑자기 사라지는 현상..(익스10) (2) 곰돌이 2025-07-13
2701340 [c++]학교 과제 질문이요...... (3) 기쁨해 2025-07-13
2701311 구글 뉴스검색최적화 작업은 누구의 영역인가요? 많은 조언 부탁드려요! 리나 2025-07-13
2701285 아이폰이나 안드로이드 폰 인터넷으로 볼때 배꽃 2025-07-12
2701230 테마 설정하면 밑에 뜨는 글 삭제 (1) 창의적 2025-07-12
2701177 css적용이 안되요~ (6) 다니엘 2025-07-11
2701151 사이트작업시 inputbox 가 readonly 형태표시 어떻게 하시나요? (1) 찬내 2025-07-11
2701123 간단한 select 질문입니다 (3) 천사의눈물 2025-07-11
2701061 비베질문.. 똘끼 2025-07-10
2701034 메일폼 내 script 삽입가능한 방법 없을까요.. (2) 마음새 2025-07-10
2701008 분명히 버튼을 만들었는데 액션이 안걸립니다. (3) 재찬 2025-07-10
2700923 전체중앙정렬&독타입&쿼크모드 ㅜㅠ (8) 푸른들 2025-07-09
2700893 질문드리겠습니다. 도도한 2025-07-09
2700793 무비클립에 마우스 오버시 랜덤으로 효과음 나기는 어떻게 ;; (1) 바닐라 2025-07-08
2700741 웹전송? (2) 연와인 2025-07-07
2700686 카테고리 호버시 세부카테고리 보이게하는 것, css로만 가능할까요?? (3) 다힘 2025-07-07
2700658 메타태그 질문드립니다..ㅠㅠ;;; 모해 2025-07-07
2700632 외부에서 이미지 파일을 불러와야 합니다. 도와주세요. (4) 에일린 2025-07-06
2700579 (air + as3) smtp 이용해서 첨부파일 포함해서 메일 보내기 물보라 2025-07-06
<<  이전  1 2 3 4 5 6 7 8 9 10  다음  >>

수다닷컴 | 여러분과 함께하는 수다토크 커뮤니티 수다닷컴에 오신것을 환영합니다.
사업자등록번호 : 117-07-92748 상호 : 진달래여행사 대표자 : 명현재 서울시 강서구 방화동 890번지 푸르지오 107동 306호
copyright 2011 게시글 삭제 및 기타 문의 : clairacademy@naver.com