新增const函数参数

This commit is contained in:
Hachi 2022-06-16 00:52:47 +08:00
parent 9f58fef2ce
commit 06d7bba7ae
5 changed files with 94 additions and 0 deletions

4
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,4 @@
{
"editor.suggest.snippetsPreventQuickSuggestions": false,
"aiXcoder.showTrayIcon": true
}

View File

@ -0,0 +1,29 @@
#include "Test.h"
#include <iostream>
using namespace std;
Test::Test()
{
cout<<"无参构造"<<endl;
}
Test::Test(int a)
{
cout<<"类型转换构造器 有参构造"<<endl;
}
Test::Test(const Test &t)
{
cout<<"拷贝构造"<<endl;
}
Test::~Test()
{
cout<<"析构函数"<<endl;
}
void Test::fun() const
{
a = 1; //mutable修饰的成员变量可以被修改
//b = 2; //非mutable修饰的变量禁止被修改
}

View File

@ -0,0 +1,20 @@
#ifndef TEST_H
#define TEST_H
class Test
{
public:
Test();
//类型转换构造函数(有参构造) 用于隐式转换
Test(int a);
//拷贝构造函数 用于显示转换
Test(const Test& t);
void fun() const;
~Test();
mutable int a;
int b;
};
#endif // TEST_H

Binary file not shown.

View File

@ -0,0 +1,41 @@
#include <iostream>
#include "Test.h"
using namespace std;
void fun(const Test& t){
t.a = 10;
}
void fun2(const Test& t){
t.a = 10;
}
void fun3(const Test& t){
t.a = 10;
}
int main()
{
Test t_m;
t_m.a = 2;
cout<<"==================================="<<endl;
cout<<"调用fun前:"<<t_m.a<<endl;//2
fun(2);//隐式转换 隐式类型转换调用类型转换构造函数 发生类型转换const引用再函数中生产临时对象
cout<<"调用fun后:"<<t_m.a<<endl;//2
cout<<"==================================="<<endl;
cout<<"调用fun2前:"<<t_m.a<<endl;//2
fun2(Test(t_m));//显示转换 显式转换调用拷贝构造函数 发生类型转换const引用再函数中生产临时对象
cout<<"调用fun2后:"<<t_m.a<<endl;//2
cout<<"==================================="<<endl;
cout<<"调用fun3前:"<<t_m.a<<endl;//2
fun3(t_m);//没有发生类型转换 不产生临时变量
cout<<"调用fun3后:"<<t_m.a<<endl;//10
return 0;
}