当前位置:编程学习 > C/C++ >>

C与C++中struct的区别

这里有两种情况下的区别。
(1)C的struct与C++的class的区别。
(2)C++中的struct和class的区别。
      在第一种情况下,struct与class有着非常明显的区别。C是一种过程化的语言,struct只是作为一种复杂数据类型定义,struct中只能定义成员变量,不能定义成员函数(在纯粹的C语言中,struct不能定义成员函数,只能定义变量)。例如下面的C代码片断:
        struct Point
        {
                int x; // 合法
                int y; // 合法
                void print()
                {
                        printf("Point print\n"); //编译错误
                };
}9        ;

        这里第7行会出现编译错误,提示如下的错误消息:“函数不能作为Point结构体的成员”。因此大家看到在第一种情况下struct只是一种数据类型,不能使用面向对象编程。

现在来看第二种情况。首先请看下面的代码:

        #include <iostream>
        using namespace std;
        class CPoint
        {
                int x;                  //默认为private
                int y;                  //默认为private
                void print()             //默认为private
                {
                        cout << "CPoint: (" << x << ", " << y << ")" << endl;
                }
        public:
                CPoint(int x, int y)      //构造函数,指定为public
                {
                        this->x = x;
                        this->y = y;
                }
                void print1() //public
                {
                        cout << "CPoint: (" << x << ", " << y << ")" << endl;
                }
        };
       
        struct SPoint
        {
                int x;              //默认为public
                int y;              //默认为public
                void print()         //默认为public
                {
                        cout << "SPoint: (" << x << ", " << y << ")" << endl;
                }
                SPoint(int x, int y)  //构造函数,默认为public
                {
                        this->x = x;
                        this->y = y;
                }
        private:
                void print1()      //private类型的成员函数
                {
                        cout << "SPoint: (" << x << ", " << y << ")" << endl;
                }
        };
       
        int main(void)
        {
                CPoint cpt(1, 2);  //调用CPoint带参数的构造函数
                SPoint spt(3, 4);  //调用SPoint带参数的构造函数
               
                cout << cpt.x << " " << cpt.y << endl;  //编译错误
                cpt.print();       //编译错误
                cpt.print1();      //合法
       
  &nb

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,