C ++类概念 - 构造函数 [英] C++ Class Concept - Constructor

查看:106
本文介绍了C ++类概念 - 构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



请查看以下代码。



Hi All,

go through below code.

class Test
{
public:
    Test()
    {
        cout<<"Constr"<<endl;
    }

    ~Test()
    {
        cout<<"Destructor"<<endl;
    }
};

int main(int argc, char* argv[])
{

    Test *test = new Test();
    Test *n = new Test;


    delete n;
    return 0;
}







对于带下划线的代码会有什么不同吗?



问候,

Ranjith




For Underlined code will make any difference?

Regards,
Ranjith

推荐答案

好吧,如果你忽略了你只删除其中一个新实例,没有。



您所做的只是声明两个变量,并创建两个单独的类实例以分配给它们。变量的名称是无关紧要的 - 类甚至无法判断它是否将保存在变量中,更不用说它的名称了!
Well, if you ignore that you only delete one of the new instances, no.

All you do is declare two variables, and create two separate instances of your class to assign to them. The name of the variable is irrelevant - the class can't even tell if it is going to be held in a variable, much less what it is called!


Test *test = new Test(); //Initialize object "test" of type "Test" with empty argument list
Test *n = new Test; //Initialize object "n" of type "Test" using default constructor





...因为你只有一个构造函数,这两个语句是等价的......如果你有多种类型的构造函数(即那些你可以传递的构造函数)初始化时的参数),你需要使用新的测试(初始化器)语法,因为 new Test 总是很简单给你默认值。



...since you only have one constructor, these two statements are equivalent... If you had more than one type of constructor (i.e. those where you can pass arguments upon initialization), you would need to use the new Test(initializers) syntax, since new Test will always simply give you the default.


这篇关于C ++类概念 - 构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆