1 Star 1 Fork 0

zeyes/cp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
useless.cpp 2.54 KB
一键复制 编辑 原始数据 按行查看 历史
zeyes 提交于 2015-08-07 22:06 +08:00 . 2015.08.07 22:06
#include <iostream>
using namespace std;
//interface
class Useless
{
private:
int n;
char *pc;
static int ct;
void ShowObject() const;
public:
Useless();
explicit Useless(int k);
Useless(int k, char ch);
Useless(const Useless & f);
Useless(Useless && f);
~Useless();
Useless operator+(const Useless & f) const;
void ShowData() const;
};
//implementation
int Useless::ct = 0;
Useless::Useless()
{
++ct;
n = 0;
pc = nullptr;
cout << "default constructor called; number of objects: " << ct << endl;
ShowObject();
}
Useless::Useless(int k) : n(k)
{
++ct;
cout << "int constructor called; number of objects: " << ct << endl;
pc = new char[n];
ShowObject();
}
Useless::Useless(int k, char ch) : n(k)
{
++ct;
cout << "int, char constructor called; Number of objects: " << ct << endl;
pc = new char[n];
for(int i = 0; i < n; i++)
pc[i] = ch;
ShowObject();
}
Useless::Useless(const Useless & f) : n(f.n)
{
++ct;
cout << "copy const called; number of objects: " << ct << endl;
pc = new char[n];
for(int i = 0; i < n; i++)
pc[i] = f.pc[i];
ShowObject();
}
Useless::Useless(Useless && f) : n(f. n)
{
++ct;
cout << "move constructor called; number of objects: " << ct << endl;
pc = f.pc;
f.pc = nullptr;
f.n = 0;
ShowObject();
}
Useless::~Useless()
{
cout << "destructor called; objects left: " << --ct << endl;
cout << "deleted object: \n";
ShowObject();
delete [] pc;
}
Useless Useless::operator+(const Useless & f) const
{
cout << "Enter operator+()\n";
Useless temp = Useless(n + f.n);
for(int i = 0; i < n; i++)
temp.pc[i] = pc[i];
for(int i = n; i< temp.n; i++)
temp.pc[i] = f.pc[i - n];
cout << "temp object: \n";
cout << "Leaving operator+()\n";
return temp;
}
void Useless::ShowObject() const
{
cout << "Number of elements: " << n << " Data address: " << (void *) pc << endl;
}
void Useless::ShowData() const
{
if(n == 0)
cout << "(Object empty)";
else
for(int i = 0; i < n; i++)
cout << pc[i];
cout << endl;
}
//application
int main()
{
{
Useless one(10, 'x');
Useless two = one;
Useless three(20, 'o');
Useless four (one + three);
cout << "Object one: ";
one.ShowData();
cout << "Object two: ";
two.ShowData();
cout << "Object three: ";
three.ShowData();
cout << "Object four: ";
four.ShowData();
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/zeyes/cp.git
git@gitee.com:zeyes/cp.git
zeyes
cp
cp
master

搜索帮助