类相关的非成员函数
函数的声明写在类的声明外部,在定义文件中去实现
testClass.h
class testClass
{
}
void printSomething(testClass& myClass);
#endif
testClass.cpp
void printSomething(testClass& myClass)
{
std::cout << "i am testClass" << std::endl;
}
类内初始化,类内的成员变量初始化
直接定义的时候就赋值,原则上是要用初始化列表的
class testClass
{
public:
int a = 1;
int b = 2;
int c = 3;
public:
testClass();
testClass(int a,int b, int c);
};
testClass::testClass(int d, int e, int f) : a(d), b(e), c(f){}
const成员的初始化,如果不在定义的时候初始化,那么所有的构造函数(拷贝函数)都要有给他赋值的语句
class testClass
{
public:
int a = 1;
int b = 2;
int c = 3;
//如果声明的时候不进行初始化
const int d;
public:
testClass();
testClass(int a,int b, int c);
};
testClass::testClass(int a) : d(1)
{
}
testClass::testClass(int d, int e, int f) : a(d), b(e), c(f), d(2)
{
}
默认构造函数,没有参数的构造函数
没有写构造函数,类就会通过默认的无参的构造函数进行构造
因为编译器默认会定义一个默认的无参构造函数,成为“合成的默认构造函数”
一旦我们写了任何一个构造函数,编译器就不会再为我们合成任何构造函数
什么情况下必须要写构造函数?
成员变量中有其他的类,并且没有无参的构造函数,所有的构造函数都要初始化这个类,参数列表也很简单,写着不麻烦
#ifndef __TESTCLASS__H__
#define __TESTCLASS__H__
class testClass2
{
public:
testClass2(int a)
{
}
};
class testClass
{
public:
int a;
int b;
int c;
public:
//如果有另外一个类,所有的构造方法都要进行该属性的初始化
testClass2 testclass2;
testClass();
explicit testClass(int a);
testClass(int d, int e, int f);
};
#endif
testClass::testClass() :testclass2(2) {}
testClass::testClass(int a) : testclass2(2){}
testClass::testClass(int d, int e, int f) : a(d), b(e), c(f),testclass2(2) {}
=default,=delete
- =defalut,在声明文件中,类的无参构造方法声明后面加上 = default ,编译器自动为我们生成函数体
- = delete,程序员显示的禁用某个函数
拷贝构造函数
拷贝构造函数会把属性挨个进行拷贝,但是如果自己定义了拷贝构造函数,那么就会完全按照自己的定义来进行
testClass class1(1, 2, 3);
testClass class2 = class1; //调用了拷贝构造函数
testClass class3(class1); //调用了拷贝构造函数
testClass class4 = { class1 }; //调用了拷贝构造函数
testClass class5{ class1 }; //调用了拷贝构造函数
testClass class6;
class6 = class1; //没有调用开拷贝构造函数,之后会进行解释
拷贝构造函数如果除了本身的引用
之外,还要加入其他的参数
的话,必须给默认值(在声明文件中,定义文件不需要)
testClass(const testClass& myself, int d = 12);
testClass::testClass(const testClass& myself, int d) : testclass2(2)
{
std::cout << "系统调用了拷贝构造函数" << std::endl;
}
建议引用使用const
建议不要加上explicit前缀
发生拷贝构造函数的其他情况
- 1、将类传递给一个非引用的函数func(class1);
void func(testClass test)
{
}
- 2、一个方法返回一个类的时候
testClass func(testClass test)
{
testClass test2 = test1;
//返回这个对象test2的时候,也是调用的拷贝函数,
//然后再返回那个拷贝的对象
return test2;
}