简体   繁体   English

使用名称创建参数化构造函数对象

[英]Parameterized Constructor Object creation using name

class Point
{
private:
int x, y;
public:
Point()
{
}
// Parameterized Constructor
Point(int x1)
{
 x=x1;
}
Point(int x1, int y1)
{
    x = x1;
    y = y1;
}
int getX()
{
    return x;
}
int getY()
{
    return y;
}
};
int main()
{
   Point p(10);
   p = Point(50,100);
}

does Point(50,100) returns an object??Can Anyone explain the details about the execution in main function. Point(50,100) 会返回一个对象吗??谁能解释一下 main 函数的执行细节。 for assigning p with Point(50,100) it should give an object.用 Point(50,100) 分配 p 它应该给出一个对象。

Here Point(50,100) creates an object then calls the assignment operator of the class Point which is generated as default by the compiler and basically copies memory of righthand operand into left hand operand.这里Point(50,100)创建一个对象,然后调用class Point的赋值运算符, class Point由编译器默认生成,基本上将右手操作数的内存复制到左手操作数中。 After copying, it also calls the destructor for the Point(50,100) .复制后,它还调用Point(50,100)的析构函数。

You can check this by adding a destructor to your function.您可以通过向函数添加析构函数来检查这一点。

~Point()
{
    std::cout<<"destructor"<<x<<std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM