类中本来就提供的成员函数,常造函数、析构函数、拷贝构造函数、拷贝赋值函数、取地址重载、取地址重载函数,C++11中还提供了:移动构造函数,移动赋值函数。
1. 构造函数:
用于初始化类的对象。构造函数名称与类名相同,没有返回值类型,可以有参数列表。使用示例如下:
class Person {
public:
Person(int a, std::string n) {
age = a;
name = n;
}
int age;
std::string name;
};
int main() {
Person p1(25, "Tom");
}
2. 拷贝构造函数:
用于创建一个新对象并将其初始化为另一个对象的副本。拷贝构造函数的名称为类名,并带有单个参数,该参数是对要拷贝的对象的引用。使用示例如下:
class Person {
public:
Person(int a, std::string n) {
age = a;
name = n;
}
Person(const Person& other) {
age = other.age;
name = other.name;
}
int age;
std::string name;
};
int main() {
Person p1(25, "Tom");
Person p2 = p1;
}
3. 成员函数:
类中定义的一种函数,操作类的数据成员。方法可公开或私有,通过类的对象来调用。使用示例如下:
class Rectangle {
public:
void setLength(double l) {
length = l;
}
double getLength() {
return length;
}
private:
double length;
};
int main() {
Rectangle r1;
r1.setLength(10.0);
double len = r1.getLength();
}
4. 析构函数:
用于在对象的生命周期结束时释放其使用的资源。析构函数名称与类名相同,前面加上“~”符号,无参数列表。使用示例如下:
class Person {
public:
Person(int a, std::string n) {
age = a;
name = n;
}
~Person() {
std::cout << "析构函数" << std::endl;
}
int age;
std::string name;
};
int main() {
Person p1(25, "Tom");
}
好的,下面列举出这三个类中常用的成员函数及其使用和代码实现:
5. 拷贝赋值函数:
用于把一个对象的值赋给另一个对象。名称为operator=,返回类型为当前对象的引用。使用示例如下:
class Person {
public:
Person(int a, std::string n) {
age = a;
name = n;
}
Person& operator=(const Person& other) {
age = other.age;
name = other.name;
return *this;
}
int age;
std::string name;
};
int main() {
Person p1(25, "Tom");
Person p2(30, "Jerry");
p1 = p2;
}
6. 取地址运算符重载:
用于定义一个取地址运算符(&)的行为,当对类对象取地址时调用该函数。名称为operator&,该函数无参数,返回类型为指向类对象的指针。使用示例如下:
class Person {
public:
int age;
std::string name;
};
Person* operator&(Person& obj) {
return &obj;
}
int main() {
Person p1 = {25, "Tom"};
Person* ptr = &p1;
}
7. 取地址重载函数:
用于允许类的对象进行类似于指针的操作,例如使用箭头符号操作对象的成员。取地址重载函数名称为operator->,仅有一个返回类型为指向类对象的指针的函数。使用示例如下:
class Person {
public:
int age;
std::string name;
std::string* operator->() {
return &name;
}
};
int main() {
Person p1 = {25, "Tom"};
std::string* ptr = p1->;
}
8.常量成员函数:
在类中声明成为常量的函数。常量成员函数有一个隐含的参数 this
,它指向调用该函数的对象,并且该参数被声明为常量。因此,常量成员函数不能修改任何数据成员,包括非可变数据成员。
#include <iostream>
using namespace std;
class Cat
{
string color;
char sex;
int age;
public:
Cat()
{
cout << "无参构造" << endl;
}
Cat(string s,char c,int a)
{
color = s;
sex = c;
age = a;
}
void set_(int mon)
{
this->age = mon;
}
void show()const
{
cout << age << endl;
}
void show()
{
cout << age << endl;
}
};
int main()
{
Cat n("w",'f',1);
n.set_(12);
n.show();
return 0;
}