我如何解决这个问题,我无法得到正确答案..? [英] How do I solve this, I am unable to get right answer..?

查看:79
本文介绍了我如何解决这个问题,我无法得到正确答案..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include   <   iostream  >  
使用 命名空间标准;
class A { int n;
protected
A( int i):n(i){}
virtual int get()= 0 < /跨度>;
virtual void print()= 0 < /跨度>;
};
int A :: get(){
return n;
}
class B: private A {
受保护
_ _ _ _1st _ _ _ _ // 定义构造函数以初始化A :: n
_ _ _ _ _ _ 2 _ _ _ _ // 覆盖get()函数返回A :: n
};
class C: public B {
public
C( int i):B(i){}
void print(){
cout<< get()<< ENDL;
}
};
int main(){
int n;
cin>> N;
C * p = new C(n);
p-> print();
return 0 ;
}





我的尝试:



在第一个空白中我面临着如何定义构造函数来初始化的问题...



而在第二个空白中,它要求覆盖在GET FUNC,在我看来,无论在基类中的get FUNC,只需将被复制为相同的基类

解决方案
您定义构造喜欢它在类 C 中完成。



你必须实现该函数,因为它被声明为基类中的纯虚拟(然后称为抽象类)。另请参见抽象类 - cppreference.com [ ^ ]。


引用:

在第一个空白我面临的问题是如何定义构造函数来初始化...

唯一明智的做法是调用基类构造函数,不是它?



引用:

而在第二个空白处,它要求覆盖get func,在我看来,无论基类中的get func,只是将被复制为与基类中的相同

A :: get 无法从 C,访问,除非 B 覆盖它( A :: get 可从 B )访问。


#include <iostream>
using namespace std;
class A { int n;
    protected:
        A(int i) : n(i) { }
        virtual int get() = 0;
        virtual void print() = 0;
};
int A::get() {
return n;
}
class B : private A {
    protected:
       _ _ _ _1st _ _ _ _ // Define the constructor to initialize A::n
     _ _ _ _ _2nd _ _ _// Override get() function to return A::n
};
class C : public B {
    public:
        C(int i) : B(i) {}
        void print() {
            cout << get() << endl;
        }
};
int main(){
    int n;
    cin >> n;
    C *p = new C(n);
    p->print();
    return 0;
}



What I have tried:

In 1st blank i am facing problem that how to define the constructor to initialize...

Whereas in 2nd blank ,it is asking for overriding the get func,in my opinion whatever the get func in the base class,simply that will be copied as same as that in the base class

解决方案

You define the constructor like it is done in class C.

You have to implement the function because it is declared pure virtual in the base class (which is then called an abstract class). See also abstract class - cppreference.com[^].


Quote:

In 1st blank i am facing problem that how to define the constructor to initialize...

The only sensible thing to do is calling the base class constructor, isn't it?

Quote:

Whereas in 2nd blank ,it is asking for overriding the get func,in my opinion whatever the get func in the base class,simply that will be copied as same as that in the base class

A::get is not accessible from C, unless B overrides it (A::get is accessible from B).


这篇关于我如何解决这个问题,我无法得到正确答案..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆