SoFunction
Updated on 2025-05-22

Interpretation of related features of C++ classes and objects

1. Type conversion

In C++, class type conversion refers to converting an object of one class to an object of another class, or converting an object of one class to a basic data type, etc.

C++ provides a variety of types of conversion mechanisms, including implicit type conversion and explicit type conversion.

The following is a detailed introduction to C++ class type conversion:

Implicit type conversion

Implicit conversion implemented by constructors

If a class's constructor has only one argument (except possible default arguments), then this constructor can be used as an implicit type conversion. For example:

class B {<!--{C}%3C!%2D%2D%20%2D%2D%3E-->
public:
    B(int x) {<!--{C}%3C!%2D%2D%20%2D%2D%3E--> /* ... */ }
};

At this time, the value of type int can be implicitly converted to an object of type B:

B b = 5; // passBThe constructor of5Implicit conversion toBObject

When the class type has multiple parameters, you can use the form of { xxx , xxx }, to convert it. You cannot use() because() will calculate the value of the last expression in brackets.

Implicit conversion implemented by type conversion operator

A class can define a type conversion operator that implicitly converts the class's object to another type. For example:

class A {<!--{C}%3C!%2D%2D%20%2D%2D%3E-->
public:
    operator int() const {<!--{C}%3C!%2D%2D%20%2D%2D%3E--> return 10; }
};

At this time, an object of type A can be implicitly converted to an int type:

A a;
int x = a; // passAThe type conversion operator willaImplicit conversion toint

This implicit conversion can cause some unexpected errors, so this implicit conversion can be disabled by preceding the constructor:

class B {<!--{C}%3C!%2D%2D%20%2D%2D%3E-->
public:
    explicit B(int x) {<!--{C}%3C!%2D%2D%20%2D%2D%3E--> /* ... */ }
};

In this way, B b = 5; will report an error, and the constructor: B b(5); must be explicitly called.

Implicit conversion between class-type objects can also be used, and the corresponding constructor supports it.

2.static members

In C++,staticMembers are an important feature of a class that is associated with the class itself, not with a specific object of the class. This meansstaticMembers are shared among all objects of the class. The following is correctstaticMember details:

static member variable

Definition and Initialization

The static member variable is a variable shared by all objects of the class. It is declared in the class definition, but needs to be initialized outside the class definition. Member variables modified with static are called static member variables. Static member variables must be initialized outside the class. For example:

class MyClass {&lt;!--{C}%3C!%2D%2D%20%2D%2D%3E--&gt;
public:
    static int count; // Declare static member variables};

int MyClass::count = 0; // initializationstaticMember variables

Note that the initialization of static member variables must be done outside the definition of the class and can only be initialized once.

Access methods

static member variables can be accessed through class names or class objects, but it is recommended to use class names to reflect their relationship with the class. For example:

MyClass::count = 10; // Access by class nameMyClass obj;
 = 20; // Access through object(Not recommended,But legal)

Whether accessed through class names or objects, static member variables are the same variable.

life cycle

The life cycle of a static member variable is initialized when the program starts running and is destroyed when the program ends. It does not depend on the life cycle of the object of the class.

Static member variables cannot be initialized to the default value at the declaration position, because the default value is a constructor initialization list. Static member variables do not belong to a certain object and do not constructor initialization list.

static member function

Definition and Call

staticA member function is a function associated with a class, not a specific object of the class. It cannot access nonstaticMember variables and nonstaticMember functions, because these members require the context of the object. For example:

class MyClass {&lt;!--{C}%3C!%2D%2D%20%2D%2D%3E--&gt;
public:
    static void print() {&lt;!--{C}%3C!%2D%2D%20%2D%2D%3E--&gt;
        std::cout &amp;lt;&amp;lt; "Static function" &amp;lt;&amp;lt; std::endl;
    }
};
Click and drag to move

staticMember functions can be called through class names or objects of the class, but it is recommended to use class names to call. For example:

MyClass::print(); // Called by class nameMyClass obj;
(); // Called through an object(Not recommended,But legal)

Features

  • staticMember functions do notthispointer, because it does not depend on specific objects.
  • It can access the classstaticMember variables and othersstaticMember function.
  • Static members are also members of the class, and are restricted by public, protected, and private access qualifiers.

Application scenarios

  • Commonly used to implement tool functions related to classes, which do not require access to member variables of the class object.
  • For example, implement a global counter:
class MyClass {
public:
    static void incrementCount() { count++; }
    static int getCount() { return count; }
private:
    static int count;
};

int MyClass::count = 0;

int main() {
    MyClass::incrementCount();
    std::cout &lt;&lt; MyClass::getCount() &lt;&lt; std::endl; // Output 1    return 0;
}

The storage location of static members

  • staticMember variables andstaticThe storage location of member functions is usually in the global data area of ​​the program. They allocate memory when the program starts and free memory when the program ends.
  • Similar to global variables,staticMember variables have a fixed address in the global data area, and all objects share this address.
  • Static member variables are shared by all class objects, do not belong to a specific object, do not exist in the object, and are stored in the static area.

Experience:

  • staticMember variables andstaticMember functions are static properties of classes that are associated with the class itself, not with the object of the class.
  • staticMember variables need to be initialized outside the class definition and can be accessed by the class name or object.
  • Member functions modified by static are called static member functionsstaticMember functions do notthisPointer, only access to classesstaticMember variables and othersstaticMember function.
  • Static member functions, which can access any static member variables and static member functions.
  • Other static members can be accessed in static member functions, but non-static members cannot be accessed because there is no this pointer.
  • By breaking through the class domain, you can access static members, and you can access static member variables and static member functions through the class name::static members or objects.static members.

Three. Friends

In C++,Friendis a very important concept, which allows certain specific functions or classes to access the private property of another class (private) and protection (protected)member.

This is very useful in some cases, especially when you need to find a balance between the encapsulation of the class and the functional requirements.

Friendly function

definition

  • A friend function is not a member function of a class, but it can access private and protected members of a class.
  • Friendly functions need to be used in the class definitionfriendKeyword declaration.

Features

  • The friend function is not a member function of the class, so it does notthispointer.
  • The definition of a friend function can be within or outside the definition of the class, but the declaration must be in the definition of the class.
  • Friend functions can access all members of a class (including private and protected members).
  • A function can be a friend function of multiple classes.

Friends category

definition

  • A friend class is a class whose member functions can access private and protected members of another class.
  • Friendly class needs to be used in the class definitionfriendKeyword declaration. For example:
class MyClass {
private:
    int privateData;

public:
    MyClass(int data) : privateData(data) {}
    friend class FriendClass; // Declare friend category};

class FriendClass {
public:
    void printPrivateData(const MyClass&amp; obj) {
        std::cout &lt;&lt; "Private Data: " &lt;&lt;  &lt;&lt; std::endl;
    }
};

In this example,FriendClassyesMyClassFriendship category, thereforeFriendClassAll member functions are accessibleMyClassPrivate members ofprivateData

Features

  • All member functions of a friend class can access private and protected members of the class declared by a friend class.
  • The declaration method of a friend class is similar to that of a friend function, but the entire class is declared.

Friend member functions

definition

  • A friend member function is a member function of another class, but it can access private and protected members of the current class. Friend member functions need to be used in the class definitionfriendKeyword declaration and specify the class and function name to which it belongs.

Features

  • A friend member function is a member function of another class, but it can access private and protected members of the current class.
  • The declaration of a friend member function requires specifying the class and function name.
  • Member functions in a metaclass can be friend functions of another class, and they can access private and protected members in another class.
  • The relationship between the friendly element class is one-way and does not have exchangeability. For example, Class A is a friend of Class B, but Class B is not a friend of Class A.
  • Friendly relationships cannot be transmitted. If A is B's friend, B is C's friend, but A is not C's friend.

summary:

  • Friendly function: Allows specific non-member functions to access private and protected members of a class.
  • Friends category: Allows all member functions of another class to access the private and protected members of the current class.
  • Friend member functions: Allows a specific member function of another class to access the private and protected members of the current class.
  • Notes on using: Use friendly elements carefully to minimize exposure to the internal structure of the class and avoid damaging the encapsulation. Friends destroy the encapsulation of a class because it allows external functions or classes to access private and protected members of a class. Therefore, you should use friend elements with caution and only use them if necessary.

IV. Internal Class

If one class is defined inside another class, this inner class is called an inner class. An inner class is a unique class. Compared with the definition globally, it is only restricted by the external class category domain and access qualifiers, so the objects defined by the external class do not contain inner classes.

The inner class is the friend class of the outer class by default.

The essence of internal classes is also a kind of encapsulation. When Class A is closely related to Class B, and Class A is mainly used for Class B. Then you can consider designing Class A as an internal class of B. If placed in the private/protected position, Class A is the exclusive internal class of Class B and cannot be used elsewhere.

The inner class and the outer class are parallel relationships. When the calculation size is calculated, the inner class is not considered as part of the outer class. The restriction of access qualifiers is received.

5. Anonymous object

Normally, we define a named object.

In C++, anonymous objects refer to objects that are not explicitly named. They are usually created when objects of a certain class need to be temporarily used and destroyed immediately after use.

The life cycle of anonymous objects is only in the current line, and it is generally only necessary to temporarily define an object and use it for the current time.

6.new

When creating an array using dynamic memory allocation (new), the constructor's calling mechanism is the same as a static array, but there are some extra considerations.

Constructor call for dynamic arrays
Sum* arr = new Sum[n];  // Dynamic creation length isnofSumArray

This line of code will:

  1. Allocate enough memory to store n Sum objects on the heap
  2. Call the default constructor for each element one by one
  3. Returns a pointer to the first element
  4. Like static arrays, the constructor will be called n times

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.