我没有得到假设的输出。 [英] I didn't get the supposed output here.

查看:68
本文介绍了我没有得到假设的输出。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;
class root{
protected:
    int value;
public:
    void setvalue(int a){
        value=a;
    }
};
class first:public root{
public:
    void print(){
    cout<<"I got the value-"<<value<<endl;
    }

};
class second:public root{
public:
    print(){
    cout<<"I got the value-"<<value<<" too"<<endl;
    }
};
int main(){
    root r;
    r.setvalue(44);
    first f;
    second s;
    f.print();
    s.print();
    return 0;

}





我的尝试:



我猜输出应该是

我得到的值44

我的值也是44



但不是这样,它给了我一个奇怪的数字代替44.



What I have tried:

I guess the output should be
"I got the value 44
I got the value 44 too"

But instead of this it is giving me a weird number in the place of 44.

推荐答案

root r;
r.setvalue(44);

在这里你创建一个类型为root的新对象r,并赋值为44.



Here you create a new object r of type root, and assign a value of 44.

first f;
second s;

在这里,您创建一个first类型的新对象f,它继承自类根,但与对象r无关。它没有用值初始化。同样的s。



Here you create a new object f of type first, which inherits from the class root, but has no relation to the object r. It is not initialised with a value. Same for s.

f.print();
s.print();

这里显示f和s的值,这些值未初始化。

Here you display the values of f and s, which are not initialised.


第二个输出是第二个对象的非inialized内存。



写一个好的构造函数,比如

The second output is non-inialized memory from the second object.

Write a good constructor like
root:root(){value = 0;}//or -1}
root:root(int inValue)



提示:编写干净代码,如类名以大字母开头,输出更清晰(输出中的类名)。


Tip: write "clean code" like class names beginning with a big letter, and clearer output (class name in output).


这篇关于我没有得到假设的输出。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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