C ++ regular object explanation-const keyword

Source: Internet
Author: User

ConstKeywords:

The definition object modified with const is called a constant object;

Declaring a member function modified by const is called a member function;

The declared data member modified by const is a common data member.

After a variable or object is modified by const, its value cannot be updated. Therefore, the variable or object modified by const must be initialized..

Common Object Description:A common object means that the data member value of an object cannot be changed when the object is called. A common object must be initialized and cannot be updated. Common member functions cannot be called through common objects, but can be called through common objects. A common object can only call a common member function. The declaration of common objects is as follows:

Const <Class Name> <Object Name>

<Class Name> const <Object Name>

There is no difference between the two statements.

 

1The following example is used to understand common objects:

A, Please point out the following program errors

Class {

PRIVATE:

Int W, h;

Public:

Int getarea () const

{

Return w * h;

}

Int getw () {return W ;}

Void setwh (int x, int y) {W = x, H = y ;}

A (int x, int y) {W = x, H = y ;}

A () {;} // This example cannot be omitted.

};

 

 

Void main ()

{

A A; // The non-object can be not initialized.

A. setwh (3,9 );

A const B; // a const B (3, 6) must be declared and initialized at the same time ).

B. setwh (); // if this sentence is used after the above correction, the error should be that B is a common object and a non-member function cannot be called. It cannot be changed when the value is switched. setwh ()

Cout <A. getarea () <Endl <B. getarea () <C. getarea ();

System ("pause ");

From: http://www.cctwl.com/CLanguageDetail.asp? Id = 65

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.