c++中 类的相关事项(1)

来源:互联网 发布:sql分组累计求和 编辑:程序博客网 时间:2024/06/08 11:15
1.类中 只有静态成员(函数)可以用类直接显示的调用
2.类中 静态成员变量static 在类外 必须重新声明并且初始化(只有这时才能给静态成员变量分配内存)
3.类中 数据成员在声明时不允许使用表达式进行初始化;
4.类中 类中数据成员在声明时,不允许使用auto,register,extern进行修饰
5.常量成员函数可以改变局部变量和全局变量的值,但不允许修改本类中数据成员的值。(常成员函数含义是通过该函数只能读取同一类中的数据成员的值,而不能修改它。如某书:
   a.常成员函数不能更新对象的数据成员
   b.当一个对象被声明为常对象,则不能通过该对象调用该类中的非const成员函数)
(非成员函数是不可以作为常量函数的 类型 函数名()const vs const int max=2;在类中这个初始化是可以的,int date[max]此时也是可以的),
6.对象成员的调用顺序取决于这些成员在类中的声明顺序,与他们在初始化列表中出现的次序无关
7.内联函数是指那些定义在类体内的成员函数,即该函数的函数体放在类体内。使用内联函数的时候要注意:
   a.递归函数不能定义为内联函数
   b.内联函数一般适合于不存在while和switch等复杂的结构且只有1~5条语句的小函数上,否则编译系统将该函数视为普通函数。
   c.内联函数只能先定义后使用,否则编译系统也会把它认为是普通函数。
   d.对内联函数不能进行异常的接口声明。
8.#include
using std::cin;
using std::cout;
using std::endl;
int main()
{
char a[]="hello";
cout<<a<<endl;//hello
cout<<*a<<endl;//h
cout<<a[0]<<endl;//h
cout<<a[1]<<endl;//e
    return 0;
}
 
9.构造函数不能显示的调用 析构函数可以显示的调用、但是!!此时 析构函数 显示和隐士的各调用了一次
     #include
using std::cout;
using std::cin;
using std::endl;
class Sample
{
  private:
     int x,y;
  public:
    Sample()
    {x=y=0;}
    Sample(int a,int b)
    {x=a;y=b;}
    ~Sample()
    {
        if(x==y)
            cout<<"x=y"<<endl;
        else
            cout<<"x!=y"<<endl;
    }
    void disp()
    {
    cout<<"x="<<x<<",y="<<y<<endl;
    }
 
};
int main()
 
{
Sample s1;
s1.disp();
s1.~Sample();
return 0;
}
 
都可以在类外部定义 如
#include
using std::cout;
using std::cin;
using std::endl;
class Sample
{
 
 
  public:
         int x,y;
    Sample();
    Sample(int a,int b)
    {x=a;y=b;}  
    ~Sample();
    void disp()
    {
    cout<<"x="<<x<<",y="<<y<<endl;
    }
 
};
Sample::Sample()
    {x=y=0;}
Sample::~Sample()
    {
        if(x==y)
            cout<<"x=y"<<endl;
        else
            cout<<"x!=y"<<endl;
    }
int main()
 
{
Sample (2,3);
//s1.~Sample();
return 0;
}
 
 
10.非正式退出函数如 exit(0)不调用析构函数
11.常量对象    作用域为仅限于表达式
#include
using std::cout;
using std::cin;
using std::endl;
class Sample
{
 
 
  public:
         int x,y;
    Sample()
    {x=y=0;}
    Sample(int a,int b)
    {x=a;y=b;}
     
    ~Sample()
    {
        if(x==y)
            cout<<"x=y"<<endl;
        else
            cout<<"x!=y"<<endl;
    }
    void disp()
    {
    cout<<"x="<<x<<",y="<<y<<endl;
    }
 
};
int main()
 
{
Sample (2,3);
//s1.~Sample();
return 0;
}
0 0