标签:函数 c++ iostream operator Once def 休息 面向对象编程 inf
先看一段类代码的定义:
#pragma once #include<iostream> using namespace std; class mycoach { public: char name[30]; int age; char expertise[60]; char foods[60]; mycoach(char *name,int age,const char* expertise); //mycoach(const mycoach& coach); ~mycoach(); void print(); void setfoodslike(char * foods); void eat(); };
#define _CRT_SECURE_NO_WARNINGS #include "mycoach.h" #include <string.h> using namespace std; mycoach::mycoach(char *_name,int age,const char * expertise):age(age) { strcpy(name,_name); cout << "I‘m " <<name<< endl; cout << "芳龄:" << age << endl; cout << "我擅长:"<<expertise <<endl; } mycoach::~mycoach() { cout << "......回宿舍休息了" << endl; } void mycoach::print() { cout << "hello~ I‘m " << name << endl; cout << "今年芳龄: " << age << endl; cout << "擅长武技: " << expertise << endl; } void mycoach::setfoodslike(char * foods) { eat(); } void mycoach::eat() { cout << "我喜欢吃:" << foods << endl; }
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include "mycoach.h" using namespace std; int main() { char coachname[30] = "陈培昌"; char* name = coachname; mycoach cpc(name,23,"泰拳,散打"); return 0; }
输出结果:
如果阅读本篇文章的你,有使用其他面向对象编程语言的经历,对于直接调用类名 对象名(初始化参数1,初始化参数2,初始化参数3.....)进行实例化的做法一定司空见惯
但偏偏作为从C有技术继承的语言C++来说,实现一个变量盛放字符串,做法十分独特-----C语言使用字符数组盛放字符串信息,C和C++都用char* 变量名指向一个字符串,C++中单设立了一个容器类型string存放字符串......
如果你习惯上述实例化一个对象的习惯,那么在c++就要留意了,对于初始化时的字符串,一定要选好变量类型,下面就各类变量选型带来的问题予以列出
以本篇中的类为例:如果mycoach类的属性name或者expertise这种字符串被声明为string类型,当然皆大欢喜,且容易想到,但是类成员方法print()中有大量cout输出调用,string类型无法cout直接输出,
结果是你不得不实现cout的多态,例如写个ostrem&operator<<(string name)函数什么的,太麻烦
char coachname[30] = "陈培昌"; char* name = coachname;
标签:函数 c++ iostream operator Once def 休息 面向对象编程 inf
原文地址:https://www.cnblogs.com/saintdingspage/p/12190062.html