符号"=",根据代码书写风格可能解释为调用不同的函数;
给程序员带来困扰的同时,程序员也不得不去了解C++是如何作函数调用的!!!
#include <iostream>
using namespace std;
struct Stack {
Stack(int a ) {
cout << "int->Stack类型转换/单参构造函数" << endl;
}
//拷贝构造函数 原则上是没必要使用explicit 声明的
Stack(Stack const& that) {
cout << "拷贝构造函数" << endl;
}
/*operator =(Stack const& that) 赋值函数*/
Stack& operator= (Stack const& that) {
cout <<"同类型 \"=\" 操作符函数" <<endl;
}
/*operator =(int const rhs) 赋值函数*/
Stack& operator= (int const rhs) {
cout << "类型 int \"=\" 操作符函数" << endl;
}
};
int main() {
/*实例化 s1,类型转换函数:编译器看到下面这句话,聪明的直接构造s1,不会有拷贝构造函数调用的*/
Stack s1 = Stack(10);
cout << "------------------" << endl;
/*匿名构造Stack(10), 然后调用拷贝赋值函数*/
s1 = Stack(10);
cout << "------------------" << endl;
/*这时编译器有几种选择,其一、把10隐式构造为Stack类型,然后拷贝赋值
其二、调用operator(int const rhs)函数,C++ 选择了调用后者*/
s1 = 10;
return 0;
}
/*
log
int->Stack类型转换/单参构造函数
------------------
int->Stack类型转换/单参构造函数
同类型 "=" 操作符函数
------------------
类型 int "=" 操作符函数
*/