[学习]C++的类 及与 结构体的区别

推荐(收藏)一篇博客:https://blog.csdn.net/u011555996/article/details/102584673

结构体默认是public的 类有public和private之分

主要还是说类吧(结构体好像是C里面用的多吧)

类包含的函数啊 还有private和public体现在哪啊 都在注释和上面博文中有体现

好了 直接看代码吧

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<string>
#include<algorithm> 
#include<cmath>
#include<vector>
#include<map>
using namespace std;
typedef long long LL;
#define PI acos(-1)
#define fin freopen("data.txt","r",stdin)
#define INF 2147483647
#define eps 1e-7
#define L 100005
#define Fo(i,a,b) for(LL i=(a),_=(b); i<=_; i++)
#define Ro(i,b,a) for(LL i=(b),_=(a); i>=_; i--)
#define Ms(a,b) memset((a),(b),sizeof(a))
#define _ceil(_,__) (_+(__-1))/__
#define debug(_) cout<<endl<<"d::"<<_<<endl<<endl
#define type(_) typeid(_).name()
inline LL read() {
    
    
	LL x = 0, f = 1;char c = getchar();
	while (!isdigit(c)) {
    
     if (c == '-')f = -f;c = getchar(); }
	while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48ll), c = getchar();
	return x * f;
}

struct Stu1 {
    
     //都是public
	string name = "Zhang San";
	int mark = 100;
	Stu1(string s, int m) {
    
    
		name = s;
		mark = m;
	}
	Stu1(const Stu1& s) {
    
    
		name = s.name;
		mark = s.mark;
	}
	string getname() const {
    
    
		return name;
	}
	int getmark() const {
    
    
		return mark;
	}
	~Stu1() {
    
    
		cout << "Destructor of Struct" << endl;
	}
};

class Stu2 {
    
     //不只有public 还有private
private: //数据成员
	string name = "Zhang San"; //赋默认值
	int mark = 100;
public:
	Stu2(string s, int m) {
    
     //默认构造函数
		name = s;
		m = mark;
	}
	Stu2(const Stu2& s) {
    
     //复制构造函数
		name = s.name;
		mark = s.mark;
	}
	string getname() const {
    
     
		return name;
	}
	int getmark() const{
    
    
		return mark;
	}
	~Stu2() {
    
     //析构函数
		cout << "Destructor of Class" << endl;
	}
};

int main() {
    
    
	Stu1 a("Li Si", 60);
	Stu2 b("Cls", 60);
	cout << a.name << " " << a.getname() << endl;
	cout << b.getname(); //这里就不能写b.name
	return 0;
}

待更,没完事儿呢。

猜你喜欢

转载自blog.csdn.net/cls1277/article/details/111670576