C++学习1

1、定义了一个名为Student的结构体,结构体包含三个成员变量:name(字符串类型指针)、age(整型)、score(浮点型)。然后,程序定义了一个函数display,用于显示结构体成员变量的信息。在main函数中,创建了一个结构体变量stu1,并为其成员变量赋值。最后,通过调用display函数展示了结构体成员变量的信息。

#include<stdio.h>
//定义结构体 
struct Student{
	//结构体包含的成员变量
	char *name;
	int age;
	float score; 
};
//显示结构体成员变量
void display(struct Student stu){
	printf("%s的年龄是%d,成绩是%f\n",stu.name,stu.age,stu.score);
}

int main(){
	struct Student stu1;
	//为结构体的成员变量赋值
	stu1.name="小明" ;
	stu1.age=15;
	stu1.score=92.5;
	//调用函数
	display(stu1);
	return 0;
}

2、 定义了一个名为Student的类,类包含了三个公有成员变量(nameagescore)和一个公有成员函数say。在main函数中,通过类来定义了一个对象stu1,并为其成员变量赋值。最后,通过调用对象的成员函数say展示了类的成员变量信息。

#include<stdio.h>
//通过class关键字类定义类
class Student{
	public:
		//类包含的变量
		char *name;
		int age;
		float score;
		//类包含的函数
		void say() {
			printf("%s的年龄是%d,成绩是%f\n",name,age,score);
		}
}; 
int main(){
	//通过类来定义变量,即创建对象
	class Student stu1;//也可以省略关键字class
	//为类的成员变量赋值
	stu1.name="小明" ;
	stu1.age=15;
	stu1.score=92.5f;
	//调用类的成员函数
	stu1.say();
	
	return 0;
}

3、演示了如何在命名空间中定义一个类Student。在main函数中,通过命名空间Diy来访问Student类,创建了一个stu1对象,并为其成员变量赋值,最后调用了say成员函数来显示信息。

//命名空间示例代码
#include<stdio.h> 
//将类定义在命名空间中
namespace Diy{
	class Student{
		public:
			char *name;
			int age;
			float score;
			
		public:
			void say(){
				printf("%s的年龄是%d,成绩是%f\n",name,age,score);
			}
	};
} 
int main(){
	Diy::Student stu1;
	stu1.name="小明";
	stu1.age=15;
	stu1.score=92.5f;
	stu1.say();
	
	return 0;
}

 4、使用了iostream库进行输入输出。程序中声明了命名空间std,定义了一个字符串变量str和一个整数变量age,然后通过cin从控制台获取用户输入,使用cout将数据输出到控制台。

//使用c++库进行输入输出
#include<iostream> 
#include<string>
int main(){
	//声明命名空间std
	using namespace std;
	
	//定义字符串变量
	string str;
	
	//定义int变量
	int age;
	//从控制台获取用户输入
	cin>>str>>age;
	//将数据输出到控制台
	cout<<str<<"已经成立" <<age<<"年了!"<<endl;
	
	return 0;
}

 5、语句在main()函数内部声明,所以它的作用范围仅限于main()函数内。当在func()函数中需要使用std命名空间时,必须在func()函数内重新声明一次。

//在 main() 函数中声明命名空间 std,它的作用范围就位于 main() 函数内部,如果在其他函数中又用到了 std,就需要重新声明
#include<iostream>
void func(){
	//必须重新声明
	using namespace std;
	cout<<"http://c.biancheng.net" <<endl;
}
int main(){
	//声明命名空间std
	using namespace std;
	cout<<"C语言中文网" <<endl;
	func();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值