18-对象的构造(中)

18-对象的构造(中)

带有参数的构造函数:

  • 构造函数可以根据需要定义参数
  • 一个类中可以存在多个重载的构造函数
  • 构造函数的重载遵循C++重载的规则
class Test {
public:
	Test(int v) {
		// use v to initialize member
	}
}

对象定义和对象声明不同:

  • 对象定义:申请对象的空间并调用构造函数
  • 对象声明:告诉编译器存在这样一个对象
Test t;    // 定义对象并调用构造函数
int main() {
	// 告诉编译器存在名为t的Test对象
	extern Test t;
	return 0;
}

构造函数的自动调用:

class Test {
public:
	Test() {}
	Test(int v) {}
};
int main() {
	Test t;        // 调用Test()
	Test t1(1);    // 调用Test(int v)
	Test t2 = 1;   // 调用Test(int v)
	
	return 0;
}

【范例代码】带参数的构造函数

#include <stdio.h>

class Test {
public:
    Test() {
        printf("Test()\n");
    }
    Test(int v) {
        printf("Test(int v), v = %d\n", v);
    }
};

int main(int argc, const char* argv[]) {
    Test t;      // 调用 Test()
    Test t1(1);  // 调用 Test(int v)
    Test t2 = 2; // 调用 Test(int v)

    int i(100);
    printf("i = %d\n", i);
    return 0;
}
构造函数的调用:
  • 一般情况下,构造函数在对象定义时被自动调用
  • 一些特殊情况下,需要手工调用构造函数

【范例代码】手工调用构造函数

#include <stdio.h>

class Test {
private:
    int m_value;
public:
    Test() {
        printf("Test()\n");
        m_value = 0;
    }
    Test(int v) {
        printf("Test(int v), v = %d\n", v);
        m_value = v;
    }
    int getValue() {
        return m_value;
    }
};

int main(int argc, const char* argv[]) {
    Test ta[3] = {Test(), Test(1), Test(2)};  // 手工调用构造函数

    for (int i = 0; i < 3; i++) {
        printf("ta[%d].getValue() = %d\n", i , ta[i].getValue());
    }
    Test t = Test(100);    // 手工调用构造函数
    printf("t.getValue() = %d\n", t.getValue());

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值