最近本人想复习下基础知识,于是写了些验证这些知识的例子
#include <fstream>
#include <string.h>
using namespace std;
ofstream out("howmany2.out");
class object;
class howmany2;
class howmany2
{
private:
enum { bufsize = 30};
char id[bufsize];
static int object_count;
int _id;
public:
howmany2(const char *ID = 0)
{
if ( ID )
{
strncpy(id, ID, bufsize);
}
else
{
*id = 0;
}
++object_count;
printf("howmany2/n/r");
}
howmany2(const howmany2 &h)
{
strncpy(id, h.id, bufsize);
strncat(id, "copy", bufsize - strlen(id));
++object_count;
printf("howmany2 (howmany2 &h)/n/r");
}
static void print(char *s)
{
printf("%s/n/r", s);
}
friend class object;
};
class object
{
howmany2 &my;
public:
object ( howmany2 &h):my(h)
{
//strncat(h.id, "object", 7);
//my = h;
my._id = 1;
printf("%d/n/r", my._id);
}
};
int howmany2::object_count = 0;
howmany2 &f(howmany2 &x)
{
howmany2 y;
return y;
}
void main()
{
howmany2 h;
howmany2 &h2 = f(h);
object ob(h);
h2.print("A");
howmany2::print("hello");
}
本文通过一个简单的 C++ 示例展示了类与对象的概念,包括如何使用静态成员变量来跟踪对象的数量,并实现了拷贝构造函数以进行深拷贝。此外,还演示了友元类的使用以及通过引用返回局部对象的行为。
728

被折叠的 条评论
为什么被折叠?



