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;
}
相关推荐
天若有情67317 小时前
从零搭建局域网手机遥控电脑网页项目,吃透工程化与架构设计思维
服务器·前端·数据库·算法·开源·node·工程化
凯瑟琳.奥古斯特17 小时前
力扣1367:二叉树中查找链表路径
数据结构·算法·leetcode·链表
tumu_C17 小时前
C++模板:Ret(Arg...)的相关
开发语言·c++·算法
Chase_______17 小时前
LeetCode 3 & 3090 题解:不定长滑动窗口——从“不重复“到“最多两次“,一个模板搞定频次约束问题
算法·leetcode
Overboom17 小时前
[BEV感知] --- IPM算法
数码相机·算法
WL_Aurora17 小时前
CentOS vs Ubuntu
linux·ubuntu·centos
大棉花哥哥17 小时前
Linux 内核本地提权漏洞(CVE-2026-31431)
linux·运维·服务器
BatyTao17 小时前
Ubuntu下载地址
linux·运维·ubuntu
HalvmånEver17 小时前
MySQL视图
linux·数据库·学习·mysql·视图
huanworld17 小时前
QT C++ UDP通信
c++·qt·udp