Understanding of struct and class

Source: Internet
Author: User

It has been thought that C + + has a class reason is that the struct in C can not have constructors, destructors, inheritance and other functions, did not expect the struct can also implement these functions.

Only the default keyword in class is private, and the default keyword in a struct is public.

An example is given to illustrate some of the functions of implementing classes with structs.

eg

#include <iostream>
using namespace Std;
Enum Breed {Golden,cairn,dandie,shetland,doberman,lab};//breed is a data type whose value can be any of the parentheses, and the first default is 0

struct mammal
{
Protected
int itsage;
int itsweight;
Public
Mammal (): Itsage (2), Itsweight (5) {}
~mammal () {}
int Getage () const {return itsage;}
void setage (int age) {itsage = age;}
int Getweight () const {return itsweight;}
void setweight (int weight) {itsweight = weight;}

void Speak () const {cout << "\ n mammal sound! \ n "; }
void Sleep () const {cout << "\ n shhh.i ' m Sleeping";}
};

struct Dog:p ublic mammal
{
Private
Breed itsbreed;
Public
Dog (): Itsbreed (GOLDEN) {}
~dog () {}
Breed Getbreed () const {return itsbreed;}
void Setbreed (Breed breed) {itsbreed = breed;}
void Wagtail () const {cout << "Tail wagging...\n";}
void Begforfood () const {cout << "begging for food...\n";}
};

int main ()
{
Dog Fido;
Fido. Speak ();
Fido. Wagtail ();
cout << "Fido is" << Fido. Getage () << "years old \ n";
return 0;
}

Output is: Mammal sound!

Tail wagging ...

Fido is 2years

Understanding of struct and class

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.