C++第16课--类的真正形态

本文学习自 狄泰软件学院 唐佐林老师的 C++课程


在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

实验1:用 class 定义类时,所有成员的默认访问级别是 private

#include <stdio.h>

struct A
{
    // defualt to public
    int i;
    // defualt to public
    int getI()
    {
        return i;
    }
};

class B
{
    // defualt to private
    int i;
    // defualt to private
    int getI()
    {
        return i;
    }
};

int main()
{
    A a;
    B b;
    
    a.i = 4;
    
    printf("a.getI() = %d\n", a.getI());
    
    b.i = 4;
    
    printf("b.getI() = %d\n", b.getI());
    
    return 0;
}


mhr@ubuntu:~/work/c++$ g++ 16-1.cpp
16-1.cpp: In function ‘int main()’:
16-1.cpp:17:9: error: ‘int B::i’ is private
     int i;
         ^
16-1.cpp:34:7: error: within this context
     b.i = 4;
       ^
16-1.cpp:19:9: error: ‘int B::getI()’ is private
     int getI()
         ^
16-1.cpp:36:38: error: within this context
     printf("b.getI() = %d\n", b.getI());
                                      ^
mhr@ubuntu:~/work/c++$ 

改:

#include <stdio.h>

struct A
{
    // defualt to public
    int i;
    // defualt to public
    int getI()
    {
        return i;
    }
};

class B
{
public:
    // defualt to private
    int i;
    // defualt to private
    int getI()
    {
        return i;
    }
};

int main()
{
    A a;
    B b;
    
    a.i = 4;
    
    printf("a.getI() = %d\n", a.getI());
    
    b.i = 4;
    
    printf("b.getI() = %d\n", b.getI());
    
    return 0;
}

mhr@ubuntu:~/work/c++$ g++ 16-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out 
a.getI() = 4
b.getI() = 4
mhr@ubuntu:~/work/c++$ 

在这里插入图片描述

在这里插入图片描述

发布了207 篇原创文章 · 获赞 100 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/LinuxArmbiggod/article/details/104097578