Java教程

实验2 继承和多态

本文主要是介绍实验2 继承和多态,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.继承访问权限测试

1.1实验要求

1.1.1设计类A具有public, protected, private等不同属性的成员函数或变量;
类B通过public, protected, private等不同方式继承A,在类B的成员函数中测试访问A的成员函数或变量;
1.1.2在类B中添加public, protected, private等不同属性的成员函数或变量,在外部测试访问B的各个成员函数或变量;
1.1.3 C以private方式继承A,尝试把A中的部分public成员提升为public。

1.2.代码实现

test.cpp

#include<istream>
#include<iostream>
using namespace std;
class A {
public:
	int _a;
protected:
	int _b;
private:
	int _c;
};

class public_B :public A {
public:
	void Test() {//测试访问A的成员函数或变量
		_a = 1;
		_b = 2;
		//_c = 3;//[Error] 'int A::_c' is private
	}
	int public_b1;
protected:
	int public_b2;
private:
	int public_b3;
};

class protected_B :protected A {//测试访问A的成员函数或变量
public:
	void Test() {
		_a = 4;
		_b = 5;
		//_c = 6;//[Error] 'int A::_c' is private
	}
	int protected_b1;
protected:
	int protected_b2;
private:
	int protected_b3;
};

class private_B :private A {//测试访问A的成员函数或变量
public:
	void Test() {
		_a = 7;
		_b = 8;
		//_c = 9;
	}
	int private_b1;
protected:
	int private_b2;
private:
	int private_b3;
};

class private_C :private A {
public:
	void Test() {
		_a = 10;
		_b = 11;
		//_c = 12;
	}
	int private_b1;
	using A::_a;
protected:
	int private_b2;
private:
	int private_b3;
};

void test()
{
	A a;
	a._a;
	std::cout<<"a._a: "<<a._a<<std::endl;
	//a._b;//[Error] 'int A::_b' is protected
	//a._c;//[Error] 'int A::_c' is private
	
	public_B s1;
	s1.Test();
	s1.public_b1;
	std::cout<<"s1.public_b1: "<<s1.public_b1<<std::endl;
	std::cout<<"s1._a: "<<s1._a<<std::endl;
	//s1._b;//[Error] 'int A::_b' is protected
	//s1._c;//[Error] 'int A::_c' is pricate
	//s1.public_b2;//[Error] 'int public_B::public_b2' is protected
	//s1.public_b3;//[Error] 'int public_B::public_b3' is private
	
	protected_B s2;
	s2.Test();
	std::cout<<"s2.protected_b1: "<<s2.protected_b1<<std::endl;
	//s2._a;s2._b;s2._c;//[Error] 'int A::_a' is inaccessible
	//s2.protected_b2;//[Error] 'int protected_B::protected_b2' is protected
	//s2.protected_b3;//[Error] 'int protected_B::protected_b2' is private
	
	private_B s3;
	s3.Test();
	std::cout<<"s3.private_b1: "<<s3.private_b1<<std::endl;
	//s3._a;s3._b;s3._c;//[Error] 'int A::_a' is inaccessible
	//s3.private_b2;//[Error] 'int protected_B::protected_b2' is protected
	//s3.private_b3;//[Error] 'int protected_B::protected_b2' is private
	
	private_C s4;
	s4.Test();
	std::cout<<"s4.private_b1: "<<s4.private_b1<<std::endl;
	//s4.private_b2;//[Error] within this context
	std::cout<<"s4._a: "<<s4._a<<std::endl;
	//s4._b;//[Error] within this context
}
int main(){
	test();
}

未完待续

这篇关于实验2 继承和多态的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!