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;
}
相关推荐
GuWenyue6 小时前
传统Agent工具两大痛点!300行代码落地MCP跨语言工具,彻底解耦LLM与工具
前端·人工智能·算法
同勉共进7 小时前
记一例 vibe coding + gcc bug 导致的线程池死锁问题
c++·线程池·gcc·死锁·vibe coding
我叫洋洋7 小时前
C ++ [ hello world ]
c语言·c++·算法
天空'之城8 小时前
C 语言工业级通用组件手写 09:CRC32 数据校验
c语言·嵌入式开发·数据校验·crc32·工业级组件
一叶龙洲8 小时前
wslg打开Ubuntu24.04默认打开图形界面
linux·服务器·数据库·ubuntu
奋发向前wcx8 小时前
y1,y2总复习笔记5 2026.7.19
数据结构·笔记·算法
敖行客 Allthinker10 小时前
Parallels Ubuntu虚拟机项目如何让手机访问?完整解决方案
linux·运维·ubuntu
王维同学11 小时前
[自学][Windows C++]RunOnceEx 注册表分组键的安全遍历
c++·windows·安全·开源
keyipatience11 小时前
线程栈与TLS和线程互斥
java·linux·服务器·开发语言·ubuntu
j7~12 小时前
【Linux】二十二.《Linux 信号机制完全指南:表示、捕捉与处理》
linux·信号处理·volatile·可入重函数·保存信号