Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

When should C++ define the constructor

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "when should C++ define the constructor", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "when should C++ define a constructor"?

C.40: if the class contains invariants, define the constructor Reason (cause)

This is the purpose of the constructor.

Example (sample) class Date {/ / a Date represents a valid date

/ / in the January 1, 1900 to December 31, 2100 range

Date (int dd, int mm, int yy)

: d {dd}, m {mm}, y {yy}

{

If (! is_valid (d, m, y)) throw Bad_date {}; / / enforce invariant

}

/ /...

Private:

Int d, m, y

}

It is usually a good idea to represent invariants through Ensure in a constructor.

Note (Note)

For convenience, you can define a constructor for a class even if it does not contain invariants.

Struct Rec {

String s

Int i {0}

Rec (const string& ss): s {ss} {}

Rec (int ii): I {ii} {}

}

Rec r1 {7}

Rec R2 {"Foo bar"}; Note (note)

The initialization list of Clippers 11 eliminates the need for many constructors. For example:

Struct Rec2 {

String s

Int i

Rec2 (const string& ss, int ii = 0): s {ss}, I {ii} {} / / redundant

}

Rec2 R1 {"Foo", 7}

Rec2 R2 {"Bar"}

The constructor of Rec2 is redundant. At the same time, the default value of int provided by the member initializer will be better.

Enforcement (implementation recommendations)

If the class contains a user-defined copy operation but does not provide a constructor (a user-defined copy is an obvious sign that the class has an invariant)

At this point, I believe you have a deeper understanding of "when C++ should define the constructor". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report