实现赋值运算符重载函数,确保:
新的数据可准确地被复制
旧的数据可准确地删除/释放
可进行 A = B = C 赋值
class Solution {
public:
char *m_pData;
Solution() {
this->m_pData = NULL;
}
Solution(char *pData) {
this->m_pData = pData;
}
// Implement an assignment operator
Solution& operator=(const Solution &object) {
// write your code here
if(this == &object )
return *this;
if (object.m_pData == NULL)
{
delete[]m_pData;
m_pData = NULL;
return *this;
}
if(m_pData!= NULL)
{
int length = strlen(object.m_pData);
delete[]m_pData;
m_pData = new char[length+1];
strcpy(m_pData,object.m_pData);
return *this;
}
}
};
实现 pow(x,n)
注意事项
不用担心精度,当答案和标准输出差绝对值小于1e-3时都算正确
class Solution {
public:
/**
* @param x the base number
* @param n the power number
* @return the result
*/
double myPow(double x, int n) {
// Write your code here
if(n == 0)
return 1;
if(x == 0)
return 0;
double y = x;
if(n > 0)
{
for(int i = 1;i < n;i++)
x=x*y;
}
if(n < 0)
{
for(int i = n; i <= 0;i++)
x=x/y;
}
return x;
}
};
新的数据可准确地被复制
旧的数据可准确地删除/释放
可进行 A = B = C 赋值
class Solution {
public:
char *m_pData;
Solution() {
this->m_pData = NULL;
}
Solution(char *pData) {
this->m_pData = pData;
}
// Implement an assignment operator
Solution& operator=(const Solution &object) {
// write your code here
if(this == &object )
return *this;
if (object.m_pData == NULL)
{
delete[]m_pData;
m_pData = NULL;
return *this;
}
if(m_pData!= NULL)
{
int length = strlen(object.m_pData);
delete[]m_pData;
m_pData = new char[length+1];
strcpy(m_pData,object.m_pData);
return *this;
}
}
};
实现 pow(x,n)
注意事项
不用担心精度,当答案和标准输出差绝对值小于1e-3时都算正确
class Solution {
public:
/**
* @param x the base number
* @param n the power number
* @return the result
*/
double myPow(double x, int n) {
// Write your code here
if(n == 0)
return 1;
if(x == 0)
return 0;
double y = x;
if(n > 0)
{
for(int i = 1;i < n;i++)
x=x*y;
}
if(n < 0)
{
for(int i = n; i <= 0;i++)
x=x/y;
}
return x;
}
};