How to create copy constructor in C++/CX with class having properties
-
22-06-2021 - |
سؤال
I'm new to C++/CX. I want to create a Vector class with two properties X and Y.
In standard C++, the copy constructor is:
Vector(const Vector& v);
I translate that to C++/CX as:
Vector(const Vector^ v);
Here's the class:
Header:
ref class Vector
{
public:
Vector();
Vector(const Vector^ v);
property double X;
property double Y;
};
Implementation:
Vector::Vector()
{
X = 0;
Y = 0;
}
Vector::Vector(const Vector^ v)
{
this->X = v->X;
this->Y = v->Y;
}
But I got an error when assigning v->X to this->X as: no instance of function "Vector::X::get" matches the argument list and object (the object as type qualifiers that prevent a match).
How to implement the copy constructor correctly?
Thanks.
المحلول
Your problem is not directly related to copy-constructors. When I compile your code, I get the following error:
'Vector::X::get' : cannot convert 'this' pointer from 'const Vector' to 'Vector %'
This shows that the problem is with const
-ness, see for example this question and its accepted answer.
It seems like the problem is that for trivial properties, the get
accessor is not declared const
. Because of that, you can't access the property on a const Vector^
.
I think a solution would be not to use trivial properties, but implement both accessors yourself, making the get
accessor const
:
private:
double x;
double y;
public:
property double X
{
double get() const { return x; }
void set(double value) { x = value; }
}
property double Y
{
double get() const { return y; }
void set(double value) { y = value; }
}
The problem with this approach is that you can't have const
methods in WinRT types (which, I assume, is why get
accessors are not const
in trivial properties). So, if you changed your type to public ref class
, you would get this error:
'get': 'const' and 'volatile' qualifiers on member functions of WinRT types are not supported
Because of that, I think your best option is to not use const
in your copy constructor:
Vector::Vector(Vector^ v)
{
this->X = v->X;
this->Y = v->Y;
}
Although I'm not sure why would you even need a copy constructor for ref class
, since you always use it as a reference.