基类对象与派生类对象指针

#include <iostream>
#include <string>

using namespace std;

class String
{
    char *name;
    int length;
    public:
        String(char *str)
        {
            length=strlen(str);
            name=new char[length+1];
            strcpy(name,str);
        }
        void show()
        {
            cout<<name<<endl;
        }
};

class de_string:public String
{
int age;
public:
    de_string(char *str, int age):String(str)
    {
        de_string::age=age;
    }
    void show()
    {
        String::show();
        cout<<"the age is:"<<age<<endl;
    }
};

int main()
{
    String s1("tony"),*ptr1;
    de_string s2("jack",20),*ptr2;
    ptr1=&s1;
    ptr1->show();
    ptr1=&s2;   //将ptr1指向String类的派生类de_string的对象s2
    ptr1->show();   //调用s2对象所属的基类的成员函数show()
    ptr2=&s2;
    ptr2 -> show();
    return 0;
}
此条目发表在C++分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Protected with IP Blacklist CloudIP Blacklist Cloud