我是C ++的新手并且遇到了这个问题。在下面的代码中,哪个语句
cout<<obj.a<<endl;
cout<<obj.b<<endl;
cout<<obj.c<<endl;
cout<<obj.c+obj.a+obj.b<<endl;
打印输出没有错误?我也坚持创建对象。如果我将obj创建为 A obj ,它也会显示错误。
#include <iostream>
using namespace std;
main(){
class A
{
protected:
int a;
private:
float b;
public:
double c;
A(int x,float y,double z)
{
a=x;
b=y;
c=z;
}
};
class B: public A
{
public:
B(int x,float y,double z): A(x,y,z)
{
}
};
class C: public B
{
public:
C(int x,float y,double z): B(x,y,z)
{
}
};
cout<<obj.a<<endl;
cout<<obj.b<<endl;
cout<<obj.c<<endl;
cout<<obj.c+obj.a+obj.b<<endl;
}
答案 0 :(得分:3)
你的代码不会工作。
以下示例将起作用:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
private:
float b;
public:
double c;
A(int x,float y,double z)
{
a=x;
b=y;
c=z;
}
int getA()
{
return a;
}
};
class B: public A
{
public:
B(int x,float y,double z): A(x,y,z)
{
}
};
class C: public B
{
public:
C(int x,float y,double z): B(x,y,z)
{
}
};
int main()
{
C obj(1,1.0,42);
cout << obj.c << endl;
cout << obj.getA() << endl;
}