Linux下练习C++的第一例

//系统为ubuntu14.04,所使用gcc version 4.8.2
在ubuntu上开发C++的第一个实例:
程序附下:
#include<iostream>
#include<string.h>
using namespace std;
class student
{
        public:
                void set(char xm[],char xb,int sx,int jsj)
                {
                        strcpy(name,xm);
                        sex=xb;
                        math=sx;
                        computer=jsj;
                }
                void print()
                {
                        cout<<"\nname is "<<name<<" sex is "<<sex<<"\nmath="<<math<<" computer="<<computer;
                }
        private:
                char name[10];
                char sex;
                int math;
                int computer;
};
int main()
{
        student s1,s2,*p1,*p2;
        p1=&s1;
        p2=&s2;
        s1.set("zhang li",'m',78,94);
        s2.set("wang fang",'f',86,56);
        s1.print();
        p1->print();
        s2.print();
        p2->print();
        return 0;
}
遇到问题:
1、头文件
使用#include <iostream.h>和#include<iostream> 是不同的。
其实2者主要的区别就是iostream是C++标准的输入输出流头文件,而iostream.h是非标准的头文件。标准头文件iostream中的函数属于标准命令空间,而iostream.h中的函数都是全局函数。
#include <iostream>//这个就是C++98标准化以后的标准头文件
#include<iostream.h> //这个就是标准化以前的头文件(当时还没有命令空间的概念)
最好使用标准头文件.
iostream是现在C++中规定的标准,目的在于使C++代码用于移植和混合嵌入时不受扩展名.h的限制,避免因为.h而造成的额外的处理和修改。
iostream包含的基本功能和对应的旧头文件相同,但头文件的内容在名字空间std中。(在标准化的过程中,库中有些部分的细节被修改了,所以旧头文件和新头文件中的实体不一定完全对应。)
一般情况下应该用这个头文件,而iostream.h则是老式的,以后有可能被淘汰。


在第二个头文件中使用#include <cstring>或者#include<string.h> 都可以得到相同的结果,刚开始使用#include<string> 发现一直编译不通,strcpy函数无法找打,可以通过man命令来找打该函数所在的头文件,具体命令为:man 3 strcpy
STRCPY(3)                                                Linux Programmer's Manual                                                STRCPY(3)


NAME
       strcpy, strncpy - copy a string


SYNOPSIS
       #include<string.h>


       char *strcpy(char *dest, const char *src);


       char *strncpy(char *dest, const char *src, size_t n);


DESCRIPTION
       The  strcpy()  function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by
       dest.  The strings may not overlap, and the destination string dest must be large enough to receive  the  copy.   Beware  of  buffer
       overruns!  (See BUGS.)
由此可以知道该函数属于的头文件为
2、GCC和G++编译
详细的区别可以百度
3、若在成员函数void set(const char xm[],char xb,int sx,int jsj)不加const会出现如下错误:e1.cpp:29:36: warning: deprecated conversion from string constant to ‘char*’详细原因百度,当时为弄明白,以后深思!


运行结果为:
dell@ubuntu:~/pan/c++/e1$ g++ -o e1 e1.cpp 
dell@ubuntu:~/pan/c++/e1$ ./e1 
name is zhang li sex is m
math=78 computer=94
name is zhang li sex is m
math=78 computer=94
name is wang fang sex is f
math=86 computer=56
name is wang fang sex is f
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值