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
的类,类包含了三个公有成员变量(name
、age
、score
)和一个公有成员函数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();
}