我是大甲鱼 发表于 2018-9-11 15:56:55

A是B的父类,B继承了A中的变量,却没继承函数。函数属性为p

#include <iostream>
#include <string>
class A
{
public :
        A(std::string thename);
        int x;
        char *str;
        char *get_char();
        std::string name;
        void print();
private:
        char *p;
};

class B:public A
{
public:
        B(std::string thename);
};


A::A(std::string thename)
{
                x=2;
                str="QWER";
                name=thename;
                p="ZXCV";
}
B::B(std::string thename):A(thename)
{
        x=3;
        str="1234";
        name=thename;

}

void A::print()
{
        std::cout<<"Aputing"<<std::endl;
}
/*
void B::print()
{
        std::cout<< "B   puting"<<std::endl;// 打开这里编译报错,B中没有这个函数
}
*/
int main()
{
        A a("A");
        B b("B");
       
        std::cout<<"x="<<b.x << "---name="<<b.name << "---str="<<b.str<<std::endl;
        std::cout<<"x="<<a.x << "---name="<<a.name << "---str="<<a.str<<std::endl;
        a.print();
        b.print();//显示A puting
          return 0;
}

BngThea 发表于 2018-9-11 16:24:31

B类中没有声明print函数,声明一下即可

claws0n 发表于 2018-9-11 16:41:04

是的,没有声明。你的类的方法应该写到类的内部吧?那个字符串的指针要固定 8,13 加 const 修饰。

我是大甲鱼 发表于 2018-9-11 19:11:20

BngThea 发表于 2018-9-11 16:24
B类中没有声明print函数,声明一下即可

变量不用声明,函数要声明吗 ?

BngThea 发表于 2018-9-12 08:34:48

我是大甲鱼 发表于 2018-9-11 19:11
变量不用声明,函数要声明吗 ?

因为你要重载这个函数,所以才需要声明
页: [1]
查看完整版本: A是B的父类,B继承了A中的变量,却没继承函数。函数属性为p