专业编程基础技术教程

网站首页 > 基础教程 正文

C++,结构体和类,结构体和类的区别,struct与class的区别

ccvgpt 2024-12-30 02:19:47 基础教程 12 ℃

C++,结构体和类,结构体和类的区别

结构体和类的唯一区别: 结构体和类具有不同的默认访问控制属性。

1、结构体中,未指定任何访问控制属性的成员,其访问控制属性为公有类型(public)。

C++,结构体和类,结构体和类的区别,struct与class的区别

2、类中,未指定任何访问控制属性的成员,其访问控制属性为公有类型(private)。

代码案例

代码案例(结构体):

#include <iostream>
using namespace std;


struct Point {
	// 未指定任何访问控制属性的成员,其访问控制属性为公有类型(public)
	int x;
	int y;
public:
	void setX(int x) {
		this->x = x;
	}
	void setY(int y) {
		this->y = y;
	}
public:
	void out() {
		cout << x << "." << y << endl;
	}
};

int main() {
	Point point1;
	point1.x = 55;
	point1.setY(55);
	point1.out();
	cout << "大小:" << sizeof(point1) << endl;
	system("pause");
	return 0;
}

代码案例(类):

#include <iostream>
using namespace std;

// 类
class Point {

	// 未指定任何访问控制属性的成员,其访问控制属性为公有类型(private)
	int x=6;
	int y=6;
public:
	void setX(int x) {
		this->x = x;
	}
	void setY(int y) {
		this->y = y;
	}
public:
	void out(){
		cout << "x" << "." << "y" << endl;
	}
};

int main() {
	Point point1;
	point1.setX(66);
	point1.setY(66);
	point1.out();
	cout << "大小:" << sizeof(point1) << endl;
	system("pause");
	return 0;
}

Tags:

最近发表
标签列表