C++复制初始化与直接初始化
最近在学习C++Primer第四版一书,看到复制初始化与直接初始化一节,其中书中说对类类型使用复制初始化总是调用类的复制构造函数,所以抄了一段测试代码研究,代码如下:
class SmallInt
{
public:
SmallInt(int i = 0) : val(i)
{
std::cout << "SmallInt::SmallInt(int i = 0)" << std::endl;
if (i < 0 || i > 255)
{
throw std::out_of_range("Bad SmallInt initializer");
}
}
SmallInt(const std::string& s) : str(s)
{
std::cout << "SmallInt::SmallInt(const string& s)" << std::endl;
}
SmallInt(const SmallInt& s) : val(s.val), str(s.str)
{
std::cout << "SmallInt::SmallInt(const SmallInt& s)" << std::endl;
}
private:
unsigned int val;
std::string str;
};
int main()
{
SmallInt si = 3.14;
SmallInt bi = std::string("aa");
return 0;
}
#include <string>
#include <iostream>
using namespace std;
class SmallInt
{
public:
SmallInt(int i = 0) : val(i)
{
std::cout << "SmallInt::SmallInt(int i = 0)" << std::endl;
if (i < 0
[解决办法]
i > 255)
{
throw std::out_of_range("Bad SmallInt initializer");
}
}
SmallInt(const std::string& s) : str(s)
{
std::cout << "SmallInt::SmallInt(const string& s)" << std::endl;
}
SmallInt(const SmallInt& s) : val(s.val), str(s.str)
{
std::cout << "SmallInt::SmallInt(const SmallInt& s)" << std::endl;
}
public:
void Func(SmallInt s){}
SmallInt Func(){return *this;}
private:
unsigned int val;
std::string str;
};
int main()
{
SmallInt si = 3.14;
SmallInt bi = std::string("aa");
SmallInt ai = bi; //调用拷贝构造
ai.Func(bi);//调用拷贝构造
ai.Func();//调用拷贝构造
return 0;
}