c++基础学习笔记——c结构体与c++类的区别

1.C结构体

结构是 C 语言的一种自定义的数据类型,在结构体中可以含有各种不同类型的数据。例如下面声明了一个复数的结构:

# include <iostream.h> 
# include <math.h>
struct complex
{ 
	double real;  // 复数的实部
    double imag; // 复数的虚部 
 	void init ( double r, double i) // 给real和imag赋初值 
 	{ 
 		read = r;
 		imag = i; 
 	} 
 	double realcomplex ( ) // 求复数的实部值
  	{ 
  		return real; 
  	} 
    double imagcomplex( ) // 求复数的虚部值
    { 
   		return imag; 
    } 
   double abscomplex( ) // 求复数的绝对值
    { 
    	double t; 
    	t = real *real + imag *imag;
     	return sqrt(t) ;
    } 
} A;

int main( ) 
{
	A .init(1.1, 2.2 ) ; 
	cout<<"real of complex A = "<<A.realcomplex( )<<endl; 
	cout<<"imag of complex A = "<<A.imagcomplex( )<<endl; 
	cout<<"abs of complex A ="<<A.abscomplex ( )<<endl;
	return 0; 
}

程序运行结果如下:
  real of complex A = 1.1
   imag of complex A = 2.2
   abs of complex A = 2.459675

在这个声明为 complex 的结构中,含有两个双精度数据 real 和 imag,分别代表复数的实数部分和虚数部分,另外含有四个属于结构 complex 的函数:init ( )、realcomplex ( )、imagcomplex( )和 abscomplex ( )。init ( ) 函数用于给 real 及 imag 赋初值,realcomplex ( )、imagcomplex( ) 和 abscomplex ( ) 三个函数分别用于计算该复 数的实部值、虚部值和绝对值。

2.C++类

结构中的数据和函数都是结构的成员,分别称作数据成员和函数成员。在C++中, 通常把函数成员称为成员函数。在这个结构中,real 和 imag 是数据成员,init ( )、 realcomplex( )、imagcomplex( )和 abscomplex( ) 是成员函数。在 C++中,一个结构的成员通常分为两类:私有成员 ( private )和公有成员 ( public )。 私有成员(包括数据和函数) 只能被该结构中的其它成员访问,而公有成员( 包括数据和函数)既可被结构内其它成员访问,也可被结构外的其它部分访问
例如在上例中,变量 real 和 imag 只需要被该结构的成员函数访问,则可声明为私有成员;四个成员函数需要在结构体外被调用,则可声明为公有成员。如下:

# include <iostream.h> 
# include <math.h> 
class complex
{ 
private : 
	double real; 
	double imag; 
public: 
	void init( double r, double i) 
	{ 
		real = r;
		imag = i; 
	} 
	double realcomplex ( ) 
	{ 
		return real; 
	} 
	double imagcomplex( )
	{ 
		return imag; 
	} 
	double abscomplex( )
 	{
 		double t ; 
 		t = real *real + imag *imag;
  		return sqrt(t) ;
   }
} A; 

int main ( ) 
	{
    	A.init( 1.1, 2.2) ; 
    	cout<<"real of complex A = "<<A.realcomplex( )<<endl;
    	cout<<"image of complex A ="<<A.imagcomplex( )<<endl; 
     	cout<<"abs of complex A ="<<A.bscomplex( )<<endl;
      	return 0 ; 
     }

可以看出,类和结构的功能基本上相同。那么在C++中为什么要用类代替结构呢?原因是,在缺省(默认)的情况下,类成员是私有的,类提供了缺省的安全性。这一规定符合面向对象思想中数据隐藏的准则。数据隐藏使得类中的成员比一般的局部变量得到更好的保护。

说明:

(1) 类的声明中的 private 和 public 两个关键字可以按任意顺序出现任意次。但是,如果把所有的私有成员和公有成员归类放在一起,程序将更加清晰。并且应该养成把所有的私有成员放在公有成员前面的习惯,因为一旦用户忘记了使用说明符 private,由于缺省值是 private,这将使用户的数据仍然得到保护。

(2)除了 private 和 public 之外,类中的成员还可以用另一个关键字 protected 来说明。被 protected 说明的成员称为保护成员,它不能被外部函数使用,但可以通过其它方法使用它,比如友元函数。

(3)数据成员可以是任何数据类型,但是不能用自动( auto)、寄存器 ( register) 或外部 ( extern)进行说明。

(4)不能在类的声明中给数据成员赋初值,例如:

class abc
{ 
private : 
	char a ='q'; 	// 错误
 	int b = 33; 	// 错误 
 public: 
 	... 
 } ;

C++规定,只有在类对象定义之后才能给数据成员赋初值

发布了31 篇原创文章 · 获赞 0 · 访问量 1265

猜你喜欢

转载自blog.csdn.net/qq_40754866/article/details/104550108