c与c++中struct的主要区别和c++中的struct与class的主要区别

1、c和c++中struct的主要区别

c中的struct不可以含有成员函数,而c++中的struct可以。

C语言

c中struct 是一种用于组合多个不同数据类型的数据成员的方式。struct 声明中的成员默认是公共的,并且不支持成员函数、访问控制和继承等概念。C中的struct通常被用于将多个相关数据组合在一起,但没有类的其他功能。

c 复制代码
struct Point {
    int x;
    int y;
};

int main() {
    struct Point p1;
    p1.x = 5;
    p1.y = 3;
    return 0;
}

C++

struct 是一种用于定义复合数据类型的方式,与C相似。然而,C++中的struct不仅可以包含数据成员,还可以包含成员函数、访问控制和继承等概念,与类(class)的功能非常接近。换句话说,C++中的struct和class的区别主要是默认的访问控制和继承方式不同。

cpp 复制代码
struct Point {
    int x;
    int y;
    void printCoordinates() {
        std::cout << "x: " << x << ", y: " << y << std::endl;
    }
};

int main() {
    Point p1;
    p1.x = 5;
    p1.y = 3;
    p1.printCoordinates();
    return 0;
}

c中的struct不可以含有成员函数,而c++中的struct可以。

2、c++中的struct与class的主要区别

c++中struct和class的主要区别在于默认的存取权限不同,struct默认为public,而class默认为private

cpp 复制代码
// 使用 struct 定义
struct MyStruct {
    int x;  // 默认 public
    void foo() { /* ... */ }  // 默认 public
private:
    int y;  // 可以显式声明为 private
};

// 使用 class 定义
class MyClass {
    int x;  // 默认 private
    void foo() { /* ... */ }  // 默认 private
public:
    int y;  // 可以显式声明为 public
};

int main() {
    MyStruct structObj;
    structObj.x = 10;  // 可以直接访问
    structObj.foo();   // 可以直接访问

    MyClass classObj;
    // classObj.x = 10;  // 错误,无法直接访问私有成员
    // classObj.foo();   // 错误,无法直接访问私有成员

    return 0;
}
相关推荐
信创工程师-小杨16 分钟前
Linux内网环境如何解决依赖的问题
linux·运维·服务器
设计师小聂!18 分钟前
宝塔 Linux 面板保姆级教程
linux·mysql·开源·运维开发
凡人叶枫24 分钟前
Effective C++ 条款16:成对使用 new 和 delete 时要采取相同形式
开发语言·c++·effective c++
菜鸟‍31 分钟前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
不吃土豆的马铃薯40 分钟前
C++ 高性能网络缓冲区 Buffer 源码解析
linux·服务器·开发语言·网络·c++
java知路42 分钟前
linux yum 下载docker安装包及依赖安装包,并离线安装
linux·运维·docker
fanged1 小时前
设备树学习2--一个DTBO实验
linux·嵌入式开发
caimouse1 小时前
Reactos 第1章 概述
c语言·开发语言·架构
星间都市山脉1 小时前
Android STS(Security Test Suite)完整介绍与测试流程
android·java·linux·windows·ubuntu·android studio·androidx
.千余1 小时前
【C++】C++继承入门(下):友元、静态成员与菱形继承的底层逻辑
开发语言·c++·笔记·学习·其他