嵌入式每日八股2.12
C++有哪几种构造函数
-
默认构造函数
没有任何参数的构造函数被称为默认构造函数。如果没有定义构造函数,则编译器会自动提供默认构造函数。默认构造函数可以用来创建对象,但是不能传递任何参数。
#include <iostream>
class MyClass {
public:
// 默认构造函数
MyClass() {
std::cout << "Default constructor called." << std::endl;
}
};
int main() {
// 使用默认构造函数创建对象
MyClass obj; // 输出: "Default constructor called."
return 0;
}
-
有参构造函数(初始化构造函数)
带有一个或多个参数的构造函数被称为带参数的构造函数。带参数的构造函数可以用来初始化对象的成员变量,可以接受一个或多个参数。
class MyClass {
public:
MyClass(int a, int b) {
// 这里可以对成员变量进行初始化,使用参数a和b
}
};
#include <iostream>
class MyClass {
public:
// 带参数的构造函数
MyClass(int value) : data(value) {
std::cout << "Constructor with parameter called. Value: " << data << std::endl;
}
private:
int data;
};
int main() {
// 使用带参数的构造函数创建对象
MyClass obj(42); // 输出: "Constructor with parameter called. Value: 42"
return 0;
}
-
拷贝构造函数
用于从一个已经存在的对象中创建一个新的对象的构造函数被称为拷贝构造函数。拷贝构造函数接受一个参数,这个参数是同类型的另一个对象的引用。它通常用于在函数参数传递或返回对象时,或者在对象赋值时进行对象的拷贝。
class MyClass {
public:
MyClass(const MyClass& other) {
// 这里可以从另一个同类型的对象other中拷贝成员变量的值
}
};
#include <iostream>
class MyClass {
public:
// 拷贝构造函数
MyClass(const MyClass& other) : data(other.data) {
std::cout << "Copy constructor called. Value: " << data << std::endl;
}
// 带参数的构造函数
MyClass(int value) : data(value) {}
private:
int data;
};
int main() {
// 使用拷贝构造函数创建对象
MyClass obj1(42);
MyClass obj2 = obj1; // 输出: "Copy constructor called. Value: 42"
return 0;
}
-
移动构造函数
用于从一个已经存在的临时对象中创建一个新的对象的构造函数被称为移动构造函数。它通常用于在对象的值被转移(比如将一个临时对象转移给一个新对象)时,避免不必要的拷贝操作,从而提高代码的性能。
class MyClass {
public:
MyClass(MyClass&& other) {
// 这里可以从另一个同类型的临时对象other中移动成员变量的值
}
};
#include <iostream>
class MyClass {
public:
// 移动构造函数
MyClass(MyClass&& other) noexcept : data(other.data) {
std::cout << "Move constructor called. Value: " << data << std::endl;
}
// 带参数的构造函数
MyClass(int value) : data(value) {}
private:
int data;
};
int main() {
// 使用移动构造函数创建对象
MyClass obj1(42);
MyClass obj2 = std::move(obj1); // 输出: "Move constructor called. Value: 42"
return 0;
}
- 转换构造函数 一个构造函数接收一个不同于其类类型的形参,可以视为将其形参转换成类的一个对象。像这样的构造函数称为转换构造函数。在 C++ string 类中可以找到使用转换构造函数的实用示例。string 类提供一个将 C 字符串转换为 string 的转换构造函数
class string
{
//仅显示转换构造函数
public:
string(char *);//形参时其他类型变量,且只有一个形参
};
【嵌入式八股】精华版(免费216问精华八股) https://www.nowcoder.com/creation/manager/columnDetail/0rOeJm
【嵌入式八股】一、语言篇https://www.nowcoder.com/creation/manager/columnDetail/mwQPeM
【嵌入式八股】二、计算机基础篇https://www.nowcoder.com/creation/manager/columnDetail/Mg5Lym
【嵌入式八股】三、硬件篇https://www.nowcoder.com/creation/manager/columnDetail/MRVDlM
【嵌入式八股】四、嵌入式Linux篇https://www.nowcoder.com/creation/manager/columnDetail/MQ2bb0