Learning the Fundamental Features of Object-Oriented Programming
Last updated on August 20, 2025 am
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
Some Basic Concepts of OOP
OOP: a class treats an object's data and the methods that operate on that data as a whole.
Class members can be variables or functions.
Class member variables are also called attributes.
Class member functions are also called methods/behaviors; class member functions can be defined outside the class.
class Student{
public:
string name;
int age;
void show(); //在类中进行声明
}
void Student::show() { //表示是成员函数
cout<<name<<" "<<age;
}Defining a class variable with a class is called creating (or instantiating) an object.
The scope and lifetime of a class's member variables and member functions are the same as the scope and lifetime of the object.
Class Access Permissions
public private protected
The differences are reflected outside the class or in derived classes
public: Accessible externally (through objects); derived classes can access it.protected: Not accessible externally, derived classes can access it.private: Not accessible externally, and derived classes also cannot access it directly.
Inside the class (in class member functions), members can be accessed regardless of whether they are declared public or private.
Outside the class (outside the code defining the class), only public members can be accessed; private and protected members cannot.
In a class body definition, private and public can appear multiple times.
Struct members default to public; class members default to private.
The purpose of private is to hide the class's data and implementation; members that need to be exposed externally are declared public.
Simple Usage of Classes
-
A class's member functions can directly access the class's other member functions.
-
Class member functions can be overloaded.
(Member functions have all the features that ordinary functions have.)
-
Class pointers are used the same way as struct pointers.
-
Class members can be of any data type (enums within a class).
class Student{
public:
enum{
boy=1,girl=2
};
}-
Default values can be specified for class members (C++11 standard).
-
Classes can create object arrays.
-
Objects can be passed as arguments to functions, generally by reference.
-
Objects can be dynamically created with
newand released withdelete. -
Outside the class, you generally don't directly access (read and write) an object's members; instead, use member functions.
-
Objects generally don't use
memset()to clear member variables; you can write a member function dedicated to clearing member variables. -
Using the
sizeofoperator on classes and objects is not very meaningful and is generally not used. -
Use structs to describe pure data, and classes to describe objects.
-
Writing classes across multiple files.
Constructors and Destructors
A constructor is a function that initializes all members of a class when the class is constructed; a destructor is a function that destroys all class members and reclaims the space they occupy when a class's life ends (when a function ends or it is deleted).
A constructor has the same name as the class, has no return type, is called automatically during construction, and can be overloaded. It can be used for initialization but cannot be called directly.
A destructor also has no return type, is called automatically during destruction, has no parameters, and cannot be overloaded. Actively calling the destructor is not recommended.
Constructor: automatically performs initialization when an object is created
Destructor: automatically performs cleanup before an object is destroyed
Constructor
Syntax: 类名(){}
Access permission must be public.
The function name must be the same as the class name.
No return value, and no void is written.
It can have parameters, can be overloaded, and can have default parameters.
It is automatically called once when an object is created and cannot be called manually.
Initialization should use the member initialization list
class T {
int a;
string s;
T(int a_, string s_) : a(a_), s(s_) { // 成员初始化列表
// 构造函数体
}
};Make sure the order in the initialization list matches the order in which the member variables are declared in the class
Destructor
Syntax ~类名(){}
Access permission must be public
The name requires a ~ before the class name
No return value, no void written
No parameters, cannot be overloaded
It is automatically called only once before the object is destroyed, but it can be called manually
Copy Constructor
Assigning one object's member variables to a new object does not call the constructor
The compiler provides one by default
Syntax 类名 (const 类名& 对象名){}
When an object is passed as a function parameter, the copy constructor is called
Shallow Copy and Deep Copy
If you perform an operation like A b=a; on a class of type A, the (default) copy constructor A(const A&) will be called to initialize b.
The effect of calling the copy constructor is divided into shallow copy and deep copy. Shallow copy means only copying the address; deep copy means copying the content at the address.
Initialization Lists
Before a constructor's function body, you can use an operation like A():a(b),c(d), which is called a member initialization list.
A member initialization list is different from assignment. Assignment is performed after the object exists, while initialization is performed directly before the object is fully constructed.
Initialization of references and const members can only be done in the member initialization list.
Initialization lists and assignment are fundamentally different: if a member is a class, using an initialization list calls the member class's copy constructor, whereas assignment first creates an object of the member class (which will call the member class's ordinary constructor) and then assigns to it.
Static data members cannot be initialized in the member initialization list
const Member Functions
Adding the const keyword after a class's member function indicates that the member function guarantees it will not modify the calling object's member variables.
Adding the mutable keyword before a member variable allows even const-qualified member functions to modify the calling object's member variable.
Non-const member functions can call both const member functions and non-const member functions.
const member functions cannot call non-const member functions.
const objects can only call const member functions.
Adding the const qualifier to constructors and destructors is illegal.
The this Pointer
If a class's member function involves multiple objects, the this pointer is needed.
The this pointer stores the object's address; it is passed to the member function as a hidden parameter and points to the object calling the member function (the caller object).
Every member function (including constructors and destructors) has a this pointer, which can be used to access the caller object's members. It can resolve the problem of member variable names being the same as function parameter names.
代码
class Student {
private:
int age;
string name;
public:
Student(int _age, string _name) : age(_age), name(_name) {}
void show() const
{
cout << age << " " << name << "\n";
}
const Student& pk(const Student& s) const
{
if (s.age > age) {
return s;
}
else {
return *this;
}
}
};
int main()
{
Student s1(18, "A"), s2(19, "B"),
s3(20, "C"), s4(21, "D");
//求出年龄最大的学生
const Student& s = s1.pk(s2).pk(s3).pk(s4);
s.show();
//21 D
return 0;
}Static Members
Including static member variables and static member functions.
They enable data sharing among multiple objects.
Ordinary objects' member variables require creating an object before they can be accessed; static member variables can be accessed without creating an object, and they must be initialized in the program's global area, requiring the class's namespace.
If a class's member is declared static, it can be separated from the class's objects. (Static members do not belong to objects)
A class's public static members behave the same as global variables and global functions.
A class's static member functions can only access the class's static members, not non-static members.
There is no this pointer in static member functions.
A class's private static members cannot be accessed outside the class.
const static member variables can be initialized when the class is defined, but without the const qualifier, they cannot.
Simple Object Model
Member functions, member variables, static member functions, and static member variables are all distributed separately in memory.
Without creating an object, accessing a non-static member variable is accessing a null pointer (at this point the this pointer is nullptr).
For program robustness, you can add code in member functions to check whether the this pointer is null.
Friends
Friends provide another way to access a class's private members.
In the C++ standard, a friend function (friend function) is never a member function of the class, even if you write its definition inside the class.
The C++ standard states:
A friend function is an external function granted access permissions; it is not a member function of the class.
Friend Global Functions
A friend global function can access all members of another class.
The friend declaration code can be placed anywhere in the class, but is generally placed at the top.
class T
{
friend void func(); //声明友元
private:
int a=1;
void show()
{
cout << a;
}
};
void func()
{
T t;
t.show(); //不会报错
}Friend Classes
Friendship cannot be inherited.
Friendship is one-way.
代码
class T
{
friend class Y; //声明友元
private:
int a=1;
void show()
{
cout << a;
}
};
class Y
{
public:
void func(T t)
{
cout<<t.a;
}
};Friend Member Functions
A friend member function can access all members of another class.
class B; // 提前声明,避免循环依赖
class A {
private:
int x;
public:
A(int v) : x(v) {}
friend void B::showA(const A& obj); // 指定 B 的成员函数是友元
};
class B {
public:
void showA(const A& obj);
};Note two points:
- Forward-declare class
Bfirst; otherwiseB::showAcannot be recognized. - Declare
B::showAwithfriendin classAso it can accessA's private members.
Operator Overloading
Syntax: 返回值 operator运算符(参数列表)
The return type of an overloaded operator function should be consistent with the operator's own meaning.
Non-member function version of overloaded operator functions: the number of parameters is the same as the number of the operator's operands.
Member function version of overloaded operator functions: one more.
代码
class T
{
public:
int x;
T(int _x):x(_x){}
T& operator+(int a) //注意,这里默认第一个参数是 this 指针
{
x+=a;
return *this;
}
};
int main()
{
T a(1);
a=a+1; //正确
//a=1+a 错误
cout<<a.x;
}If you want to implement 1+a, you must write it as a non-member function (or friend) overload.
Also, the + overload here isn't quite right; overloading += would be more appropriate.
代码
class T {
public:
int x;
// 构造函数
T(int _x): x(_x) {}
// 1️⃣ += 运算符(修改自身)
T& operator+=(const T& other) {
x += other.x;
return *this;
}
// 2️⃣ + 运算符(T + T)
T operator+(const T& other) const {
return T(x + other.x); // 返回新对象
}
// 3️⃣ + 运算符(T + int)
T operator+(int a) const {
return T(x + a); // 返回新对象
}
// 4️⃣ + 运算符(int + T)—— 必须是非成员
friend T operator+(int lhs, const T& rhs) {
return T(lhs + rhs.x); // 返回新对象
}
};
int main() {
T a(1);
// 1. 支持 T + int
cout << (a + 3).x << endl; // 输出 4
// 2. 支持 int + T
cout << (3 + a).x << endl; // 输出 4
// 3. 支持 T + T
cout << (a + a).x << endl; // 输出 2
// 4. 支持 a += (a + 3)
a += (a + 3); // a = 1 + (1+3) = 5
cout << a.x << endl; // 输出 5
// 5. 支持 a += (a + (a + 3))
a += (a + (a + 3)); // 计算步骤:a+(a+3)=5+(5+3)=13, a+=13 -> 18
cout << a.x << endl; // 输出 18
return 0;
}this is T*, so *this is an lvalue.
If the return type is T&, then return *this returns a reference to the current object.
引用
In C++, lvalues and rvalues are core concepts of expression classification. Once you understand these concepts, you'll understand why
return *thiscan return a reference, and why some expressions can have their address taken while others cannot. Below I'll explain in detail with simple language and examples.
1️⃣ Definitions
Lvalue
- lvalue = location value
- Represents an object that has a definite address in memory and whose address can be taken
- Can usually appear on the left side of an assignment (hence "lvalue")
For example:
int x = 10; int* p = &x; // ✅ x 是左值,有地址
Rvalue
- rvalue = read value
- A temporary value or literal that has no stable memory address (its address cannot be taken)
- Can usually only appear on the right side of an assignment
For example:
int x = 10; 10 = x; // ❌ 10 是右值,不能赋值 int* p = &10; // ❌ 字面量没有可取的地址
2️⃣ Common Examples
int a = 5; int b = 10; a = b; // ✅ a 是左值,b 是左值(表达式结果是右值) a = a + b; // a 是左值,(a+b) 是右值
- Lvalue expressions: variable names, dereferences
*p, function calls returning references- Rvalue expressions: literals, arithmetic expressions, function calls returning values (non-references)
3️⃣ Lvalues, Rvalues, and Function Returns
int x = 5; int& foo1() { return x; } // 返回左值引用 int foo2() { return x; } // 返回值 foo1() = 10; // ✅ 返回左值引用,可以赋值 foo2() = 10; // ❌ 返回右值,临时对象不可赋值This also explains why in operator overloading:
operator+=returnsT&, because we want it to be an lvalue, supporting chained assignmentoperator+returnsT, because the result is a temporary value and should be an rvalueSummary Mnemonic
- Lvalue: can have its address taken, has a name, can be placed on the left of
=- Rvalue: a temporary value, no stable address, can usually only be placed on the right of
=- Returning a reference → lvalue
- Returning a value → rvalue (unless it's a
staticlocal or due to optimization)
Overloading Relational Operators
== != > < >= <=
Overloading the Left Shift Operator
Overloading the left shift operator can only use the non-member function version.
To output a class's private members, you can use friends.
代码
class T
{
std::string name;
int age;
public:
T(std::string _name, int _age) : name(_name), age(_age) {}
void show()
{
std::cout << name<<" " << age;
}
friend std::ostream& operator << (std::ostream& os, const T& t)
{
os << t.name<<" " << t.age;
return os;
}
};
int main()
{
T t("A", 18);
t.show();
std::cout << std::endl;
std::cout << t;
}Overloading the Subscript Operator
[]
If an object contains an array, overloading the subscript operator makes operating on the array inside the object as convenient as operating on an ordinary array.
Syntax
返回值类型& operator[] () {}
and
const 返回值类型& operator[] () {}
In actual development, both versions should be provided together, in order to accommodate const objects, because const objects can only access const functions.
The overloaded function can perform validity checks on the subscript to prevent array out-of-bounds access.
代码
class T
{
std::string names[3];
public:
T(std::string _name, std::string __name, std::string ___name)
{
names[0] = _name;
names[1] = __name;
names[2] = ___name;
}
std::string& operator[] (int ii)
{
return names[ii];
}
const std::string& operator[] (int ii) const
{
return names[ii];
}
};
int main()
{
T t("A", "B", "C");
std::cout << t[0] << std::endl;
t[0] = "D";
std::cout << t[0] << std::endl;
const T t1("E", "F", "G");
std::cout << t1[0] << std::endl;
return 0;
}Overloading the Assignment Operator
Exists by default.
After overloading, the default one is no longer called.
Overloading the new delete Operators
*void represents a block of memory space independent of data type.
Overloading the Parenthesis Operator
The parenthesis operator function can only be overloaded as a class member function, not as a global function.
It can implement a functor.
Everything behaves like a function, but in essence it is not a function.
It has wide applications in templates and the STL.
Overloading Unary Operators
Mainly the increment and decrement operators, because they can be placed on either the left or the right.
C++ specifies that when overloading ++ and --, if the overloaded function has an int parameter, the compiler will call this overloaded function when processing postfix expressions.
代码
class T
{
int x;
public:
T(int _x) : x(_x) {}
T& operator++ ()
{
x++;
return *this;
}
T operator++ (int) //后置的用法
{
T temp = *this; //因为后置的不可以嵌套
x++;
return temp;
}//返回值不可以是引用,成员函数的临时变量不能引用
void show()
{
std::cout << x;
}
};
int main()
{
T t(1);
++(++t);
t.show();
std::cout << std::endl;
(t++)++; //这个链式运算是没有意义的
t.show(); //输出 4
}Automatic Type Conversion
Converting some data type to the class's type.
In C++, a single-parameter constructor is used as an automatic type conversion function; it happens automatically and does not require explicit conversion.
class T
{
int x;
public:
T(int _x) : x(_x) {}
};
int main()
{
T t1(1); //常规写法
T t1 = T(8); //强制类型转换
t1 = 9; //隐式转换
}- A class can have multiple conversion functions.
- For a multi-parameter constructor, if all parameters except the first have default values, it can also serve as a conversion function.
- If an automatic type conversion is ambiguous, compilation will fail.
Using constructors as automatic type conversion functions seems like a nice feature, but sometimes it leads to unexpected type conversions. The explicit keyword is used to turn off this automatic behavior, but explicit conversions are still allowed.
Conversion Functions
Converting a class to some type.
Syntax: operator 数据类型()
代码
class T
{
int x;
std::string name;
public:
T(int _x, std::string _name) : x(_x), name(_name) {}
operator int()
{
return x;
}
operator std::string()
{
return name;
}
};
int main()
{
T t(18, "A");
int x = t; //隐式
std::cout << x << std::endl;
std::string s = t; //隐式
std::cout<< s << std::endl;
std::cout << int(t) << " " << std::string(t); //显式
}Note: a conversion function must be a class member function; it cannot specify a return type; it cannot have parameters.
If an implicit conversion is ambiguous, the compiler will report an error.
Another approach is to replace the conversion function with an ordinary member function with the same functionality; an ordinary member function only executes when called. This is more recommended.
For example:
string s1 = "ABC"; //char*转换为 string
const char* s2 = s1; //报错,不存在这样的转换函数
//cpp 在 string 类里面提供了一个成员函数
const char* s2 = s1.c_str();Implicit conversions should be used with caution.
Class Inheritance
Inheritance: the process by which one class obtains members from another class.
The class being inherited from: the base class or parent class.
The class that inherits: the derived class or child class.
Syntax
class T{
/*
*/
};
class G:public T
{
...
}Inheritance Methods
public protected private
When class B inherits from class A, the permissions of base class members in the derived class are affected by the inheritance method:
Base class member public inheritance protected inheritance private inheritance publicremains publicin the derived classbecomes protectedin the derived classbecomes privatein the derived classprotectedremains protectedin the derived classremains protectedin the derived classbecomes privatein the derived classprivatecannot be inherited (invisible) cannot be inherited (invisible) cannot be inherited (invisible) 📌 Note: regardless of the inheritance method, the base class's
privatemembers are never inherited into the derived class (even if inherited, they cannot be accessed).
Since private and protected inheritance methods change the access permissions of base class members in the derived class, making the inheritance relationship complicated, in actual development, public is generally used.
In a derived class, the base class's private members can be accessed indirectly through the base class's public member functions.
The using keyword can change the access permissions of base class members in the derived class.
代码
class A
{
public:
int a;
protected:
int b;
private:
int c;
};
class B : public A
{
//原本来说,a 是 public 的,b 是 protected 的,c 是不可见的
//现在使用 using 进行调整
public:
using A::b;
private:
using A::a;
};Note: using can only change the access permissions of public and protected members in the base class; it cannot change the access permissions of private members, because the base class's private members are invisible in the derived class and cannot be used at all.
The Object Model of Class Inheritance
When a derived class object is created, the base class's constructor is called first, then the derived class's constructor.
When a derived class object is destroyed, the derived class's destructor is called first, then the base class's destructor.
When a derived class object is created, memory is allocated only once; the derived class object contains the base class object's memory space, and the this pointer is the same.
When a derived class object is created, the base class object is initialized first, then the derived class object.
How to Construct the Base Class
The key points of derived class constructors are as follows:
-
When a derived class object is created, the program first calls the base class constructor, then the derived class constructor.
-
If no base class constructor is specified, the base class's default constructor will be used.
-
The initialization list can be used to specify which base class constructor to use.
-
The base class constructor is responsible for initializing the inherited data members; the derived class constructor is mainly used to initialize the newly added data members.
-
The derived class's constructor always calls a base class constructor, including the copy constructor.
The base class's member variables must be initialized by the base class's constructor!
Name Hiding and Class Scope
If a member in the derived class (including member variables and member functions) has the same name as a member in the base class, when that member is used through a derived class object or in the derived class's member functions, the derived class's newly added member will be used, not the base class's.
Base class member functions and derived class member functions do not form overloads; if the derived class has a function with the same name, it will hide all functions with the same name in the base class.
代码
class A
{
public:
int a = 10;
void func()
{
cout << "a";
}
//重载成员函数
void func(int x)
{
cout << x;
}
};
class B : public A
{
public:
int a = 20;
void func()
{
cout<<"b";
} //注释掉这个函数就不会报错(不会遮蔽)
};
int main()
{
B b;
b.func(1); //会报错
}Adding the class name and scope resolution operator before a member name allows access to the object's members. If there is no inheritance relationship, the class name and scope resolution operator can be omitted.
When there is an inheritance relationship, the base class's scope is nested within the derived class's scope. If a member is found in the derived class's scope, the search will not continue in the base class's scope; if not found, the search continues in the base class's scope. (This is why name hiding occurs.)
If the class name and scope resolution operator are added before a member, that scope's member can be used directly.
Special Relationships in Inheritance
There are some special relationships between derived classes and base classes:
If the inheritance method is public, derived class objects can use base class members.
A derived class object can be assigned to a base class object (including private members), but non-base-class members will be discarded.
A base class pointer can point to a derived class object without explicit conversion.
A base class reference can refer to a derived class object without explicit conversion.
Multiple Inheritance and Virtual Inheritance
class C : public A, public B {};
Diamond inheritance:
A has two subclasses B, C, and D inherits from B, C.
This causes ambiguity and redundancy.
Add the virtual keyword:
class C : virtual public A, virtual public B {};
Class Polymorphism
A base class pointer can only call the base class's member functions, not the derived class's member functions.
If the virtual keyword is added before a base class's member function, declaring it as a virtual function, the base class pointer can call the derived class's member function with the same name, and through that same-named member function in the derived class, the derived object's member variables can be accessed.
With virtual functions, when a base class pointer points to a base class object, it uses the base class's member functions and data; when it points to a derived class object, it uses the derived class's member functions and data. The base class pointer exhibits multiple forms; this phenomenon is called polymorphism.
Base class references can also use polymorphism.
-
Only the function declaration in the base class needs the virtual keyword; it cannot be added in the function definition.
-
When redefining a virtual function in a derived class, the function signature must be the same.
-
When a virtual function is defined in the base class, if the derived class does not redefine it, the base class's virtual function will be used.
-
The rules of name hiding and function overloading also apply to virtual functions.
-
When a virtual function has been redefined in the derived class, if you want to use the base class's function, you can add the class name and scope resolution operator.
-
If you intend to redefine a base class function in the derived class, make it virtual; otherwise, do not make it virtual. There are two benefits: first, it is more efficient; second, it indicates that the function should not be redefined.
Application Scenarios of Polymorphism
- The base class's virtual functions implement basic functionality
- Derived classes redefine virtual functions to extend functionality, improve performance, and implement customized features
How to Destroy Derived Classes
After a derived class's destructor finishes executing, the base class's destructor is automatically executed.
To ensure the stability of polymorphism, set the base class's destructor to be a virtual function.
Constructors and destructors cannot be inherited.
Assignment operator functions and friend functions cannot be inherited.
The destructor can be called manually; if the object contains heap memory, this code in the destructor is necessary:
delete ptr;
ptr = nullptr;For a base class, even if it doesn't need a destructor, it should provide an empty virtual destructor.
Pure Virtual Functions and Abstract Classes
Pure virtual function: a function in the base class that doesn't need any default implementation or functionality.
virtual void func() = 0;A class containing pure virtual functions is called an abstract class; it cannot instantiate objects, but pointers and references can be created.
A pure virtual destructor must have a code implementation. The point is that sometimes you want a class to be an abstract class, but it happens to have no pure virtual functions. What to do? Solution: declare a pure virtual destructor in the class you want to make abstract.
Runtime Type Identification and the dynamic_cast Keyword
Runtime Type Identification (RTTI) allows a program to determine an object's type at runtime; it only applies to classes containing virtual functions.
The dynamic_cast operator converts a pointer to a base class into a pointer to a derived class.
Syntax: 派生类指针 = dynamic_cast<派生类类型 *> (基类指针)
dynamic_cast only applies to classes containing virtual functions.
The typeid Operator and the type_info Class
The typeid operator
- Is a runtime type identification (RTTI) mechanism provided by C++.
- Usage:
typeid(expression) - Returns a
const std::type_info&object describing the expression's actual type.
The type_info class
- Is a class defined in the
<typeinfo>header file that encapsulates type information. - You cannot directly create
type_infoobjects, but you can obtain a reference to one throughtypeid. - Common methods:
name(): returns a platform-dependent type name (usually mangled, requiringabi::__cxa_demangleto decode).before(): used for sorting types.operator==,operator!=: compare whether types are the same.
Function Templates
A function template is a generic data type, describing functions with arbitrary data types (generics).
The process of generating a function definition is called instantiation.
template <typename T>
void Swap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
int b = 20;
Swap(a, b);
cout << a << " " << b << endl;
}If you don't want the compiler to automatically deduce the data type, you can write it like this:
int main()
{
int a = 10;
int b = 20;
Swap <int> (a, b);
cout << a << " " << b << endl;
}Notes on Function Templates
Templates can be created for class member functions, but not for virtual functions and destructors.
When using a function template, the data type must be explicit, ensuring the actual arguments can match the function template.
When using a function template, the deduced data type must be compatible with the code in the function template.
When using a function template, if automatic type deduction is used, no implicit type conversion occurs; if the function template's data type is explicitly specified, implicit type conversion can occur.
Function templates support multiple generic data type parameters.
template <typename T1, typename T2>
void func(T1 a, T2 b)
{
cout << a << " " << b;
}Function templates support overloading and can have non-generic data type parameters.
Specifics of Function Templates
You can provide a specialized function definition; when the compiler finds a specialized definition matching the function call, it will use that definition and no longer look for the template.
Syntax: template < > 函数定义(非通用数据类型的参数列表)
< > is empty!
The compiler's rule order for using functions: ordinary functions, function templates, specialized function templates, overloaded functions
Advanced Function Templates (cpp11+)
The decltype keyword
An operator used to query the data type of an expression.
Syntax: decltype(expression) var;
This operator returns the data type, which can be used to define variables.
For example, decltype(1+1) a; is equivalent to int a;.
This operator only analyzes the type and does not execute the expression.
Some rules:
-
If expression is an identifier not enclosed in parentheses, then var's type is the same as the identifier's type, including qualifiers such as const.
-
If expression is a function call, then var's type is the same as the function's return type (the function cannot return void, but it can return void*).
-
If expression is an lvalue (whose address can be taken) (excluding the first case), or an identifier enclosed in parentheses, then var's type is a reference to expression.
-
The lvalue case:
int a = 1; decltype(++a) b; //b 的类型是 int& -
The parentheses case:
int a = 1; decltype(a) b; //b 的类型是 int decltype((a)) b; //b 的类型是 int&
-
-
If none of the above conditions are met, then var's type is the same as expression's type.
Trailing Return Types for Functions
int func()
{
}
// 等价于
auto func() -> int
{
}Here auto acts as a placeholder.
This is meaningful when a function template's return type is undetermined.
template <typename T1, typename T2>
auto add(T1 a, T2 b) -> decltype(a+b) //必须写在后面,cpp 的解释是后面才是 a 和 b 的作用域
{
return a+b;
}The auto Keyword in C++14
cpp14 made an optimization: functions can directly use auto as the return type without needing a trailing return type.
template <typename T1, typename T2>
auto add(T1 a, T2 b)
{
return a+b;
}Class Templates
Function templates are recommended to use typename to describe generic data types; class templates are recommended to use class.
Notes:
When creating objects, the specific data type must be specified.
When using a class template, the data type must be compatible with the code in the class template.
Class templates can specify default data types for generic parameters (function templates under the C++11 standard can too).
Class member functions can be implemented outside the class.
Template objects can be created with new. The class name is A <...>, and the template class name is A.
代码
template <class T1, class T2>
class A
{
public:
T1 x;
T2 y;
A() {} //需要提供默认构造函数
A(T1 x, T2 y) : x(x), y(y) {}
void print() const {
cout << "x: " << x << ", y: " << y << endl;
}
};
int main()
{
A<int, double> a;
A<int, double> b(1, 2.5);
a.print();
b.print();
return 0;
}Example of Class Templates: Stack
The most common use of class templates is as container classes
代码
template <class T>
class myStack
{
private:
int* items;
int itop;
int size;
public:
myStack(int _size):
size(_size), itop(-1)
{
items = new int[size];
}
~myStack()
{
delete[] items;
}
bool push(T item)
{
if (itop == size - 1) {
return false;
}
else {
items[++itop] = item;
return true;
}
}
bool pop()
{
if (itop == -1) {
return false;
}
else {
itop--;
return true;
}
}
bool iempty()
{
return itop == -1;
}
T top()
{
if (itop == -1) {
throw runtime_error("Stack is empty");
}
else {
return items[itop];
}
}
};
int main()
{
myStack<int> s(5);
s.push(1);s.push(2);s.push(3);s.push(4);s.push(5);
while(!s.iempty()) {
cout << s.top() << " ";
s.pop();
}
}Example of Class Templates: Array
The most important thing is to overload the subscript operator
Class templates can have non-generic type parameters:
- Usually integer types (the C++20 standard allows other types)
- Constant expressions must be used when instantiating the template
- The value of the parameter cannot be modified inside the template.
Fixed-Length Array Container
代码
template <class T, int len>
class myArray
{
private:
int a[len];
public:
myArray()
{
}
T& operator[] (int idx)
{
return a[idx];
}
const T& operator[] (int idx) const
{
return a[idx];
}
};
int main()
{
myArray<int, 5> arr;
for (int i = 0; i < 5; ++i) {
arr[i] = i;
}
for (int i = 0; i < 5; ++i) {
cout << arr[i] << " ";
}
}Variable-Length Array Container
代码
template <class T>
class myVector
{
private:
int len;
T* v;
public:
myVector (int _len) :
len(_len)
{
v = new T[len];
}
~myVector()
{
delete[] v;
v = nullptr;
}
void resize (int _len)
{
if (_len < len) {
return;
}
else {
T* temp = new[_len];
for (int i = 0; i < len; ++i) {
temp[i] = v[i];
}
delete[] v;
v = temp;
delete[] temp;
temp = nullptr;
len = _len;
}
}
int size()
{
return _len;
}
T& operator[] (int idx)
{
if (idx >= _len) {
resize(len * 2);
}
return v[idx];
}
const T& operator[] (int idx) const {
return v[idx];
}
};Nesting and Recursive Use of Class Templates
The most common case: a container inside a container
You must rewrite the copy constructor and assignment function, otherwise shallow copy problems will occur
Specialization of Class Templates
Priority: more specialized > less specialized > not specialized
代码
template <class T1, class T2>
class A
{
public:
void show()
{
cout << "没有具体化版本" << endl;
}
};
template <class T>
class A <T, int>
{
public:
void show()
{
cout << "部分具体化版本" << endl;
}
};
template <>
class A <int, int>
{
public:
void show()
{
cout << "完全具体化版本" << endl;
}
};Class Templates and Inheritance
A Class Template Inheriting from an Ordinary Class
Just arrange the base class's constructor properly. Note: the way a derived class constructs its base class is by calling the base class's constructor through the initialization list of the derived class's constructor. If you don't write it, the compiler will automatically call the base class's default constructor (if it exists).
An Ordinary Class Inheriting from an Instantiated Version of a Class Template
This is just ordinary inheritance
An Ordinary Class Inheriting from a Class Template (Common)
代码
template <class T1, class T2>
class Base
{
private:
T1 x;
T2 y;
public:
Base(T1 _x, T2 _y) : x(_x), y(_y)
{
cout << "Base" << endl;
}
};
template <class T1, class T2>
class Derived : public Base<T1, T2>
{
private:
int z;
public:
Derived(T1 _x, T2 _y, int _z) :
Base<T1, T2>(_x, _y), //注意这里构造函数的写法
z(_z)
{
cout << "Derived" << endl;
}
};A Class Template Inheriting from a Class Template
代码
template <class T1, class T2>
class Base
{
private:
T1 x;
T2 y;
public:
Base(T1 _x, T2 _y) : x(_x), y(_y)
{
cout << "Base" << endl;
}
};
template <class T, class T1, class T2>
class Derived : public Base<T1, T2>
{
private:
T z;
public:
Derived(T1 _x, T2 _y, T _z) :
Base<T1, T2>(_x, _y), //注意这里构造函数的写法
z(_z)
{
cout << "Derived" << endl;
}
};A Class Template Inheriting from a Base Class Given by a Template Parameter
The base class is undetermined, can be changed, and can be passed as a parameter
代码
template <class T>
class A
{
public:
T t;
A() {}
A(T _t) : t(_t)
{
}
void show()
{
cout << t << endl;
}
};
template <class T>
class B : public T
{
public:
B() : T() //需要保证基类一定存在默认构造函数
{
}
};Class Templates and Functions
Class templates can be used as function parameters and return values, in three forms:
-
Ordinary functions, where the parameters and return value are instantiated versions of a class template.
-
Function templates, where the parameters and return value are some kind of class template.
-
Function templates, where the parameters and return value are of any type (supporting ordinary classes, class templates, and other types).
Class Templates and Friends
Non-Template Friends
The tricky part is that you cannot prepare a function for every instantiated version of a class template and declare it as a friend
cpp provides a solution: use the class template's parameters to automatically generate friend functions
template <class T1, class T2>
class A
{
T1 t1;
T2 t2;
public:
friend void show(const A <T1, T2)& a)
{
cout << t1 << t2 << endl;
}
};However, this friend function is not a function template! This means that if we want to create a special version of the friend function for a particular data type, it cannot be done. Also, the friend function generated this way can only be used with this class template, and not with other class templates.
代码
template <class T1, class T2>
class A
{
private:
T1 t1;
T2 t2;
public:
friend void show(const A <T1, T2>& a)
{
cout << t1 << t2 << endl;
}
friend void show(const A <int ,int>& a);
};
void show(const A <int ,int>& a)
{
cout << a.t1 << a.t2 << endl; //这一行报错
}This kind of friend is called a non-template friend, and it can only be implemented inside the class
Constrained Template Friends
When a class template is instantiated, each instantiated class corresponds to one friend function
-
Step one, before the definition of the class template, declare the friend function template
template <typename T> void show(T& a); -
Step two, inside the class template, declare the friend function template again
template <class T1, class T2> class A { friend void show <> (A <T1, T2>& a); //<> 表示这里的 show 是模板函数的显式实例,不是普通函数。 T1 t1; T2 t2; public: A(T1 _t1, T2 _t2) : t1(_t1), t2(_t2) { } }; -
Step three, the definition of the friend function template
template <typename T> void show(T& a) { cout << "通用" << a.t1 << " " << a.t2 << endl; }Because the friend function is a function template, it can have specialized versions
template < > void show(A <int, string>& a) { cout << "特化" << a.t1 << " " << a.t2 << endl; }
This can also support multiple class templates (just write it repeatedly)
Unconstrained Template Friends
Not commonly used in development, so I won't bother writing it.
Member Templates of Class Templates
This means creating class templates and function templates inside a class template
Using Class Templates as Parameters
Let's assume that Array and Stack are both implementations of a LinearList,
and then use a template template parameter to implement a generic LinearList interface, so that you can pass in different implementations.
Example Code
代码
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
// ===== 线性表实现 1:数组形式 =====
template <typename T>
class ArrayList {
public:
void insert(const T& value) {
data.push_back(value);
}
void remove() {
if (!data.empty()) data.pop_back();
}
T getLast() const {
return data.back();
}
void show() const {
for (auto& v : data) cout << v << " ";
cout << endl;
}
private:
vector<T> data;
};
// ===== 线性表实现 2:栈形式 =====
template <typename T>
class StackList {
public:
void insert(const T& value) { // 入栈
data.push(value);
}
void remove() { // 出栈
if (!data.empty()) data.pop();
}
T getLast() const { // 栈顶
return data.top();
}
void show() const {
// 栈没有直接遍历接口,这里为了演示复制一份遍历
stack<T> tmp = data;
while (!tmp.empty()) {
cout << tmp.top() << " ";
tmp.pop();
}
cout << endl;
}
private:
stack<T> data;
};
// ===== 通用线性表类:模板模板参数 =====
template <template <typename> class Impl, typename T>
class LinearList {
public:
void add(const T& value) {
impl.insert(value);
}
void removeLast() {
impl.remove();
}
void showAll() const {
impl.show();
}
T getLast() const {
return impl.getLast();
}
private:
Impl<T> impl; // 用模板模板参数来实例化
};
int main() {
// 使用数组实现的线性表
LinearList<ArrayList, int> arrList;
arrList.add(1);
arrList.add(2);
arrList.add(3);
arrList.showAll(); // 1 2 3
cout << "Last: " << arrList.getLast() << endl;
cout << "-----" << endl;
// 使用栈实现的线性表
LinearList<StackList, int> stackList;
stackList.add(10);
stackList.add(20);
stackList.add(30);
stackList.showAll(); // 30 20 10
cout << "Last: " << stackList.getLast() << endl;
return 0;
}Key Points
-
ArrayList and StackList are two different implementations, but their method names are consistent (
insert,remove,getLast,show). -
LinearList is a generic interface that uses a template template parameter:
template <template <typename> class Impl, typename T>Implis a class template (e.g.,ArrayList,StackList)Tis the data type being stored
-
In this way,
LinearList<ArrayList, int>andLinearList<StackList, int>will automatically adapt to different underlying implementations.``