随笔-145  评论-173  文章-70  trackbacks-0
首先来看看下面这段代码:
#include <iostream>
using namespace std;
class test
{
public:
    test(int a,float b)
    {
        x =  a;
        y = b;
    }
    void show()
    {
        cout << "x = " << x << endl
            << "y = " << y << endl;
    }
private:
    int x ;
    float y;
};
void main()
{
    test b(1,3.2);
    b.show();
}
完全没有问题,自己定义了一个构造函数,而不是系统默认的构造函数,这样就不会出错了!!
然后看看下面的这段代码:
#include <iostream>
using namespace std;
class test
{
public:
    void show()
    {
        cout << "x = " << x << endl
            << "y = " << y << endl;
    }
private:
    int x;
    double y;
};
void main()
{
    test b(1,3.2);
    b.show();
}
然后就会出错,为什么,因为默认的构造函数是没有形参,所以你传递进去的两个形参就会报错!更不可能把你的那两个参数赋值给它的private内容中的形参。
还可以定义一个函数专门进行赋值化或者初始化,这样就相当于一个构造函数,可是实现起来的话就要显示的调用set函数。
class test
{
public:
    void set(int a,float b)
    {
         x = a;
         y = b;
    }
    void show()
    {
         cout << "x = " << x << endl
            << "y = " << y << endl;
    }
private:
    int x;
    float y;
};

void main()
{
    test b;
    b.set(1,3.4);
    b.show();
}
posted on 2009-11-27 21:42 deercoder 阅读(446) 评论(0)  编辑 收藏 引用 所属分类: C/C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理