2. 下面是一个非常简单的类定义:
(……代码省略……)
它使用了一个string对象和一个字符数组,让您能够比较它们的用法。请提供未定义的方法的代码,以完成这个类的实现。再编写一个使用这个类的程序,它使用了三种可能的构造函数调用(没有参数、一个参数和两个参数)以及两种显示方法。下面是一个使用这些构造函数和方法的例子:
Person one; // use default constructor
Person two("Smythecraft"); // use #2 with one default argument
Person three(:Dimwiddy", "Sam"); // use #2, no defaults
one.Show();
cout << endl;
one.FormalShow();
// etc. for two and three
头文件:
#pragma once
#ifndef PERSON_H_
#define PERSON_H_
#include<string>
class Person {
private:
static const int LIMIT = 20;
std::string lname;
char fname[LIMIT];
public:
Person() { lname = "\0"; fname[0] = '\0'; };
Person(const std::string& ln, const char* fn = "Heyyou!");
~Person();
void show() const;//保证函数不会修改调用对象!
void Formalshow()const;
};
#endif
类方法声明:
#include<iostream>
#include "person.h"
Person::Person(const std::string& ln, const char* fn /*= "Heyyou!"错误!*/) {//注意在成员函数定义中不能出现默认值!!!
lname = ln;
//fname[LIMIT] = *fn;
strcpy_s(fname, fn);//字符串赋值用该语句!!!!!!!!
}
Person::~Person()
{
}
void Person::show() const {
std::cout << fname << "\0" << lname << std::endl;
}
void Person::Formalshow() const {
std::cout << lname << "," << fname << std::endl;
}
程序:
#include "person.h"
#include <iostream>
int main() {
{
Person p1;
p1.show();
p1.Formalshow();
Person p2{ "Smythecraft" };
p2.show();
p2.Formalshow();
Person p3;
p3 = Person{ "CJ","无敌" };
p3.show();
p3.Formalshow();
Person p4 = Person{ "Dimwiddy","Sam" };
p4.show();
p4.Formalshow();
}
return 0;
}