weijun_yang
#include <string.h>
#include <stdio.h>
class Base
{
private:
char *name;
public:
Base(char *className)
{
if (NULL == className)
{
name = new char[1];
*name = '\0';
}
else
{
name = new char[strlen(className)+1];
strcpy(name, className);
}
}
~Base()
{
delete [] name;
}
char * copyName()
{
/*char newname [256];
strcpy(newname, name);
return newname; */
char *pNewName = name;
return pNewName;
}
virtual char * getName()
{
return name;
}
static void print(Base &base)
{
printf("name: %s\n" , base.name);
}
};
class Subclass : public Base
{
public:
Subclass(char * className) : Base(className)
{
}
};
int main(void)
{
Base * pBase = new Subclass("test");
Base::print(*pBase);
printf("name: %s\n", pBase->getName());
printf("new name: %s\n", pBase->copyName());
return 0;
}
注意:(建议去读读C/C++高质量程序设计)
1。strcpy(name, className); // strcpy 复制时带 '\0', 所以 new 的时候应该多分配一个字符。
2。return newname; 不要返回指向栈内存的指针或引用,因为函数返回后栈回收。
3。static void print(Base base) 参数应该写成引用方式(Base &base),因为你没有编写拷贝构造函数与复制函数。