#include <iostream>
using namespace std;
class Student{
private:
char *name;
int age;
float score;
public:
//声明构造函数
Student(char *, int, float);
//声明普通成员函数
void say();
};
//定义构造函数
Student::Student(char *name1, int age1, float score1){
name = name1;
age = age1;
score = score1;
}
//定义普通成员函数
void Student::say(){
cout<<name<<"的年龄是 "<<age<<",成绩是 "<<score<<endl;
}
int main(){
//根据构造函数创建对象
Student stu("小明", 15, 90.5f); //传参形式类似于函数调用
stu.say();
return 0;
}
小明的年龄是 15,成绩是 90.5
Student(){}
#include <iostream>
using namespace std;
class Student{
private:
char *name;
int age;
float score;
public:
//声明构造函数
Student();
Student(char *, int, float);
//声明普通成员函数
void setname(char *);
void setage(int);
void setscore(float);
void say();
};
//定义构造函数
Student::Student(){}
Student::Student(char *name1, int age1, float score1){
name = name1;
age = age1;
score = score1;
}
//定义普通成员函数
void Student::setname(char *name1){
name = name1;
}
void Student::setage(int age1){
age = age1;
}
void Student::setscore(float score1){
score = score1;
}
void Student::say(){
cout<<name<<"的年龄是 "<<age<<",成绩是 "<<score<<endl;
}
int main(){
//创建对象时初始化成员变量
Student stu1("小明", 15, 90.5f);
stu1.say();
//调用成员函数来初始化成员变量的值
Student stu2;
stu2.setname("李磊");
stu2.setage(16);
stu2.setscore(95);
stu2.say();
return 0;
}
小明的年龄是 15,成绩是 90.5 李磊的年龄是 16,成绩是 95
构造函数名(类型1 形参1, 类型2 形参2, …)
类名 对象名(实参1, 实参2, …);
#include <iostream>
using namespace std;
class Box
{
public :
Box(int,int,int);
int volume( );
private :
int height;
int width;
int length;
};
//声明带参数的构造函数//声明计算体积的函数
Box::Box(int h,int w,int len) //在类外定义带参数的构造函数
{
height=h;
width=w;
length=len;
}
int Box::volume( ) //定义计算体积的函数
{
return (height*width*length);
}
int main( )
{
Box box1(12,25,30); //建立对象box1,并指定box1长、宽、高的值
cout<<"The volume of box1 is "<<box1.volume( )<<endl;
Box box2(15,30,21); //建立对象box2,并指定box2长、宽、高的值
cout<<"The volume of box2 is "<<box2.volume( )<<endl;
return 0;
}
The volume of box1 is 9000 The volume of box2 is 9450
Box::Box(int h,int w,int len):height(h),width(w), length(len){ }
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有