栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【星海出品】C++的基础(通过代码学习)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【星海出品】C++的基础(通过代码学习)

一个学员的信息,保存到一个 txt 文件中。
#include 
#include 
#include 
using namespace std;

class Student{
	public:
		int num;
		char name[20];
		int core;
	friend void save();
	friend void view();
};

void view(Student *s2){
	cout << s2->num << endl;
	cout << s2->name << endl;
	cout << s2->core << endl;
}

void save(Student *s2){
	int i;
	fstream fs; //文件流对象 
	fs.open("user.txt",fstream::in | fstream::out |fstream::app);  //目标 
	fs.seekg(0, ios::end);
	
	ofstream destFile("out.txt",ios::in);//以文本模式打开in.txt
	if(!destFile){ //打开失败 
		cout << "error opening destination file." << endl; 
	}
	for(int i=0;i<1;i++)
		destFile << s2->num << " ";
		destFile << s2->name << " ";
		destFile << s2->core << " ";
	
	destFile.close();
	
	
}

main(){
	Student s1;
	cout << "please input you studentNum: " << endl;
	cin >> s1.num;
	cout << "you studentNum is : " << s1.num << endl;
	
	cout << "please input you name" << endl;
	cin >> s1.name;
	cout << "you name is :" << s1.name << endl;
	
	cout << "please input you core : " << endl;
	cin >> s1.core;
	cout << "you core is : " << s1.core << endl;
	
	view(&s1);
	save(&s1);

}
C++的钻石继承
#include 
using namespace std;
class A{
	int a;
	public:
		A(int n){
			a=n;
			cout << "A::a=" << a << endl;
		}
		~A(){
			cout << "A的对象在消亡" << endl; 
		};
};

class B{
	int b;
	public:
		B(int n1,int n2){
			b=n1;
			cout << "B::b=" << b << endl;
		}
		~B(){
			cout << "B的对象在消亡" << endl; 
	    };
};

class C:public A,public B{
	int c;
	public:
		C(int n1,int n2, int n3,int n4):B(n3,n4),A(n2){
			c=n1;
			cout << "C::c=" << c << endl;
		}
		~C(){
			cout << "C的对象在消亡" << endl; 
		};
};

int main(){
	C Cobj(1,3,5,7);
	return 0;
}

结果展示:
A::a=3
B::b=5
C::c=1
C的对象在消亡
B的对象在消亡
A的对象在消亡

C++ 类模板
//类模板中成员函数的创建时机
#include 
using namespace std;

class Person1
{
public:
	void showPerson1()
	{
		cout << "Person1 show" << endl;
	}
};

class Person2
{
public:
	void showPerson2()
	{
		cout << "Person2 show" << endl;
	}
};

template
class Myclass
{
public:
	T obj;
	
	//类模板中的成员函数在调用的时候才创建,所以不会报错
	void func1()
	{
		obj.showPerson1();
	}

	void func2()
	{
		obj.showPerson2();
	}
};

void test01()
{
	Myclassm;
	m.func1();
	//m.func2(); 无法调用
};

int main()
{
	test01();
	system("pause");
	return 0;
}

结果: Person1 show
类模板的声明还可以是template

#include 
using namespace std;
class Test{
	private:
		int n;
	public:
		Test(int i=16){
			n=--i;
		}
		int Get(){
			return n;
		}
		int Get()const {
			return(n-2);
		}
};
 
int main(){
	Test a;
	const Test b(27);
	cout << a.Get() << endl;
	cout << b.Get() << endl;
	return 0; 
}

结果 15 24

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1011307.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号