//系统为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