您的位置:首页 > 其它

第十二周 课后实践:程序阅读(5)

2015-06-03 08:06 405 查看
问题及代码:

#include <iostream>
using namespace std;
class A
{
protected:
int a,b;
public:
A(int aa, int bb):a(aa), b(bb) {}
void printA()
{
cout<<"a: "<<a<<"\tb: "<<b<<endl;
}
};
class B: public A
{
int c;
public:
B(int aa, int bb, int cc):A(aa,bb),c(cc) {}
void printB()
{
cout<<"a: "<<a<<"\tb: "<<b<<"\tc: "<<c<<endl;
}
};
int main()
{
A a(1,1);
B b(2,3,4);
//此处加入下面各小题中的代码
return 0;
}


(a)

a=b;
a.printA();
b.printA();
b.printB();

输出结果:



(b)

b=a;
a.printA();
b.printA();
b.printB();


错误原因:基类不能赋值给派生类。

记录下IDE中提示的错误并理解:F:\新建文件夹\a\main.cpp||In function 'int main()':|

F:\新建文件夹\a\main.cpp|29|error: no match for 'operator=' in 'b = a'|

F:\新建文件夹\a\main.cpp|29|note: candidate is:|

F:\新建文件夹\a\main.cpp|14|note: B& B::operator=(const B&)|

F:\新建文件夹\a\main.cpp|14|note: no known conversion for argument 1 from 'A' to 'const B&'|

||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===|

(c)

A &r1=a;
A &r2=b;
r1.printA();
r2.printA();
r2.printB();


输出结果:



错误的一行:r2.printB()。.原因是r2是基类中的,不能输出派生类中的。

(d)

A *p=&a;
p->printA();
p=&b;
p->printA();
p->printB();


输出结果:



错误的一行:p->printB();。原因是p是基类中的,不能输出派生类中的。

(e)

#include <iostream>
using namespace std;
class A
{
protected:
int a,b;
public:
A(int aa, int bb):a(aa), b(bb) {}
void printA()
{
cout<<"a: "<<a<<"\tb: "<<b<<endl;
}
int getA(){return a;}
};
class B: public A
{
int c;
public:
B(int aa, int bb, int cc):A(aa,bb),c(cc) {}
void printB()
{
cout<<"a: "<<a<<"\tb: "<<b<<"\tc: "<<c<<endl;
}
};
void f(A x)
{
cout<<"aaaaah,my a:"<<x.getA()<<endl;
}
int main()
{
A a(1,1);
B b(2,3,4);
f(a);
f(b);
//此处加入下面各小题中的代码
return 0;
}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: