2.1 类和对象(第二章 C++面向对象程序设计) 联系客服

发布时间 : 星期日 文章2.1 类和对象(第二章 C++面向对象程序设计)更新完毕开始阅读6091c11067ec102de2bd89f6

void main() {

person demo;

demo.init(30,”LiMing”); demo.display(); }

运行结果:LiMing is 30 years odl. 程序3:

#include #include class person { int age; char*name; public:

void init(int i,char *str) { int j;

j=strlen(str)+1;

name=new char[j]; strcpy(name,str); age=i; }

~person()

{ delete name;

cout<<”destructor is called.\\n”; }

void display()

{ cout<

void main() { person demo;

demo.init(30,”LiMing”); demo.display(); }

运行结果:LiMing is 30 years old.

destructor is called. 程序4:

#include class CSam {

public:

static int m; CSam() {m++;} CSam(int n) {m=n;}

static void testm() {m++;} };

int CSam::m=0; void main() {

CSam A; CSam B(3); A.testm(); CSam::testm();

cout<<”m=”<

14、定义一个描述学生基本情况的类,数据成员包括姓名、学号、C++、英语和数学成绩,成员函数包括输出数据、置姓名和学号、置3门课的成绩,求出总成绩和平均成绩。

#include #include using namespace std;

class Student { public:

Student(string nm=\ cpp(0), english(0), math(0) { }

void set_name_number(string na, string nmb) {

name = na; number = nmb; }

void set_grade(int _cpp, int eng, int ma) {

cpp = _cpp; english = eng; math = ma; }

void sum() {

cout << \ }

void average() {

cout << \ }

void display() {

cout << name << \ << number << \ << cpp << \ << english << \ << math << endl; } private:

string name; string number; int cpp; int english; int math; };

void main() {

Student a;

a.set_name_number(\ a.set_grade(53.4, 45.2, 34.6); a.sum(); a.average(); a.display(); }

15、设有一个描述坐标点的CPoint类,其私有变量x和y代表一个点的x、y坐标值。编写程序实现以下功能:利用构造函数传递参数,并设其默认值为60和75,利用成员函数display()输出这一默认的值;利用公有成员函数setpoint()将坐标值修改为(80,150),并利用成员函数输出修改后的坐标值。

#include using namespace std;

class CPoint { public:

CPoint(int _x=60, int _y=75):x(_x), y(_y) { } void display() {

cout << \ }

void setpoint() {

x = 80; y = 150; } private: int x; int y; };

void main() {

CPoint a;

cout << \