Sdílet prostřednictvím


class (C++)

The class keyword declares a class type or defines an object of a class type.

[template-spec] class [ms-decl-spec] [tag [: base-list ]]
{
   member-list
} [declarators];
[ class ] tag declarators;

Parameters

  • template-spec
    Optional template specifications. For more information, refer to Template Specifications.

  • class
    The class keyword.

  • ms-decl-spec
    Optional storage-class specification. For more information, refer to the __declspec keyword.

  • tag
    The type name given to the class. The tag becomes a reserved word within the scope of the class. The tag is optional. If omitted, an anonymous class is defined. For more information, see Anonymous Class Types.

  • base-list
    Optional list of classes or structures this class will derive its members from. See Base Classes for more information. Each base class or structure name can be preceded by an access specifier (public, private, protected) and the virtual keyword. See the member-access table in Controlling Access to Class Members for more information.

  • member-list
    List of class members. Refer to Class Members for more information.

  • declarators
    Declarator list specifying the names of one or more instances of the class type. Declarators may include initializer lists if all data members of the class are public. This is more common in structures, whose data members are public by default, than in classes. See Overview of Declarators for more information.

Remarks

For more information on classes in general, refer to one of the following topics:

For information on managed classes and structs, see Classes and Structs

Example

// class.cpp
// compile with: /EHsc
// Example of the class keyword
// Exhibits polymorphism/virtual functions.

#include <iostream>
#include <string>
#define TRUE = 1
using namespace std;

class dog
{
public:
   dog()
   {
      _legs = 4;
      _bark = true;
   }

   void setDogSize(string dogSize)
   {
      _dogSize = dogSize;
   }
   virtual void setEars(string type)      // virtual function
   {
      _earType = type;
   }

private:
   string _dogSize, _earType;
   int _legs;
   bool _bark;

};

class breed : public dog
{
public:
   breed( string color, string size)
   {
      _color = color;
      setDogSize(size);
   }

   string getColor()
   {
      return _color;
   }

   // virtual function redefined
   void setEars(string length, string type)
   {
      _earLength = length;
      _earType = type;
   }

protected:
   string _color, _earLength, _earType;
};

int main()
{
   dog mongrel;
   breed labrador("yellow", "large");
   mongrel.setEars("pointy");
   labrador.setEars("long", "floppy");
   cout << "Cody is a " << labrador.getColor() << " labrador" << endl;
}

See Also

Reference

C++ Keywords

Classes, Structures, and Unions