C ++, 생성자 뒤의 콜론은 무엇을 의미합니까? [복제]
가능한 중복 :
C ++ 생성자 구문 질문 에서 콜론 뒤의 변수
생성자
여기에 C ++ 코드가 있습니다.
class demo
{
private:
unsigned char len, *dat;
public:
demo(unsigned char le = 5, unsigned char default) : len(le)
{
dat = new char[len];
for (int i = 0; i <= le; i++)
dat[i] = default;
}
void ~demo(void)
{
delete [] *dat;
}
};
class newdemo : public demo
{
private:
int *dat1;
public:
newdemo(void) : demo(0, 0)
{
*dat1 = 0;
return 0;
}
};
내 질문은 무엇입니까입니다
: len(le)
및
: demo(0, 0)
전화?상속과 관련이 있습니까?
다른 사람들이 말했듯이, 그것은 초기화 목록입니다. 두 가지 용도로 사용할 수 있습니다.
- 기본 클래스 생성자 호출
- 생성자 본문이 실행되기 전에 멤버 변수를 초기화합니다.
사례 1의 경우, 상속을 이해한다고 가정합니다 (그렇지 않은 경우 의견에 알려주십시오). 따라서 기본 클래스의 생성자를 호출하면됩니다.사례 # 2의 경우, "생성자의 본문에서 초기화하지 않는 이유는 무엇입니까?" 초기화 목록의 중요성은 특히
const
회원들에게 분명합니다 . 예를 들어
m_val
생성자 매개 변수를 기반으로 초기화하려는이 상황을 살펴보십시오 .
class Demo
{
Demo(int& val)
{
m_val = val;
}
private:
const int& m_val;
};
C ++ 사양에 따르면 이것은 불법입니다.
const
const로 표시되어 있으므로 생성자 의 변수 값을 변경할 수 없습니다 . 따라서 초기화 목록을 사용할 수 있습니다.
class Demo
{
Demo(int& val) : m_val(val)
{
}
private:
const int& m_val;
};
const 멤버 변수를 변경할 수있는 유일한 시간입니다. 그리고 Michael은 의견 섹션에서 언급 한 것처럼 반원 인 참조를 초기화하는 유일한 방법이기도합니다.
Outside of using it to initialise const
member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.
This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++
It's called an initialization list. It initializes members before the body of the constructor executes.
It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.
If you use =
to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.
It means that len
is not set using the default constructor. while the demo
class is being constructed. For instance:
class Demo{
int foo;
public:
Demo(){ foo = 1;}
};
Would first place a value in foo before setting it to 1. It's slightly faster and more efficient.
You are calling the constructor of its base class, demo.
참고URL : https://stackoverflow.com/questions/2785612/c-what-does-the-colon-after-a-constructor-mean
'programing' 카테고리의 다른 글
개발 및 프로덕션 환경에서 다른 Web.config 사용 (0) | 2020.05.14 |
---|---|
.NET에서 '클로저'란 무엇입니까? (0) | 2020.05.14 |
Android의 Java 7 언어 기능 (0) | 2020.05.14 |
언제 Cassandra를 복용해서는 안되나요? (0) | 2020.05.14 |
3D 게임은 어떻게 그렇게 효율적입니까? (0) | 2020.05.14 |