第二章 掌握C++(1)从结构到类

  C++与C相比有许多优点,主要体现在封装性(Encapsulation)、继承性(Inheritance)和多态性(Polymorphism)。封装性是把数据与操作数据的函数组织在一起,不仅使程序结构更加紧凑,并且提高了类内部数据的安全性;继承性增加了软件的可扩充性及代码重用性;多态性使设计人员在设计程序时可以对问题进行更好的抽象,有利于代码的维护和可重用。

  在C语言中,我们可以定义结构体类型,将多个相关的变量包装为一个整体使用。在结构体中的变量,可以是相同、部分相同,或完全不同的类型数据。在C语言中,结构体不能包含函数。而在C++中结构体可以包含函数。

  2.1.1结构体的定义

#include<iostream>
using namespace std;

struct point
{
    int x;
    int y;
};

int main()
{
    point pt;
    pt.x = 0;
    pt.y = 0;
    cout<<pt.x<<" "<<pt.y<<endl;
    return 0;
}

  注意,在定义结构体时,一定不要忘了在右花括号处加上一个分号。

  下面,将输出函数写在结构体中,代码就变成:

#include<iostream>
using namespace std;

struct point
{
    int x;
    int y;
    void output()
    {
        cout<<x<<" "<<y<<endl;
    } 
};

int main()
{
    point pt;
    pt.x = 0;
    pt.y = 0;
    pt.output();
    return 0;
}

  2.1.2结构体与类

  将上面的point结构体定义中的关键字struct换成class,如下:

class point
{
    int x;
    int y;
    void output()
    {
        cout<<x<<" "<<y<<endl;
    } 
};

  在默认情况下,结构体成员是公有(public)的,而类的成员是私有(private)的。在类中,公有成员是可以在类的外部进行访问的,而私有就只能在类的内部进行访问。所以,2.1.1中的代码直接只将struct换成class再运行时会出错,因为我们访问了类的私有成员。

  所以,将其都改为公有的也就可以运行了。

#include<iostream>
using namespace std;

class point
{
public:
    int x;
    int y;
    void output()
    {
        cout<<x<<" "<<y<<endl;
    } 
};

int main()
{
    point pt;
    pt.x = 0;
    pt.y = 0;
    pt.output();
    return 0;
}

  

原文地址:https://www.cnblogs.com/xueniwawa/p/3999464.html