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:
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
getaccessor is not declaredconst. Because of that, you can’t access the property on aconst Vector^.I think a solution would be not to use trivial properties, but implement both accessors yourself, making the
getaccessorconst:The problem with this approach is that you can’t have
constmethods in WinRT types (which, I assume, is whygetaccessors are notconstin trivial properties). So, if you changed your type topublic ref class, you would get this error:Because of that, I think your best option is to not use
constin your copy constructor:Although I’m not sure why would you even need a copy constructor for
ref class, since you always use it as a reference.