面向对象【3】

//类和结构体类型的异同
//结构体和类的作用基本上是一样的,也就是说结构体也可以当做类来使用,但是为什么有类还会有结构体呢?这是因为C++是以C为基
//础的C语言的扩充语言,所以要照顾C语言的使用者,能使拥有C结构体的代码可以不加修改的在C++的环境下运行;
// 一、用sturct声明的结构体,如果对其中的成员不做public和private的声明话,则系统会将这些数据设置成默认的public类型;
// 二、用class声明的结构休,如果对其中的成员不做public和private的声明的话,则系统会将这些数据设置成默认的private类型;
// 下面两个例子来说明上面的两个定义;

//class例子:
		
#include <iostream>
using namespace std;

class myclass
{
	int a;
	int b;
//public:   //如果将这里的注释去掉的话,就可以成功的运行了;
	void setnumber(int x,int y)
	{
		a = x;
		b = y;
	}
	void display()
	{
		cout<<"a:"<<a<<endl<<"b"<<b<<endl;
    }
};
int main()
{
	myclass test;
		test.setnumber(10,20);
		test.display();
		system("pause");
	return 0;
}
//下面是错误代码:
//=======================================================================================
//[BCC32 Error] File1.cpp(22): E2247 'myclass::setnumber(int,int)' is not accessible
//  Full parser context
//    File1.cpp(20): parsing: int main()
//=======================================================================================

		sturct例子:
//
#include <iostream>
using namespace std;

struct myclass
{
	int a;
	int b;
//public:
	void setnumber(int x,int y)
	{
		a = x;
		b = y;
	}
	void display()
	{
		cout<<"a:"<<a<<endl<<"b"<<b<<endl;
    }
};
int main()
{
	myclass test;
		test.setnumber(10,20);
		test.display();
		system("pause");
	return 0;
}


 

//如果将class改为struct这个程序就没有任何的问题了,通过上面两个例子可以很清楚的知道了结构体与类区别;
//以class声明的自定义类型,如果不指定public或是private的话则系统默认就是private;
//以struct声明的自定义类型,如果不指定public或是private的话则系统默认就是public;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值