c++ - 如何在 C++/CX 中使用具有属性的类创建复制构造函数

标签 c++ windows-runtime c++-cx

我是 C++/CX 新手。我想创建一个具有两个属性 X 和 Y 的 Vector 类。

在标准 C++ 中,复制构造函数是:

Vector(const Vector& v);

我将其翻译为 C++/CX:

Vector(const Vector^ v);

这是类(class):

标题:

ref class Vector
{
public:
    Vector();
    Vector(const Vector^ v);

    property double X;
    property double Y;
};

实现:

Vector::Vector()
{
    X = 0;
    Y = 0;
}

Vector::Vector(const Vector^ v)
{
    this->X = v->X;
    this->Y = v->Y;
}

但是在将 v->X 分配给 this->X 时出现错误:没有函数“Vector::X::get”的实例与参数列表和对象匹配(该对象作为阻止匹配的类型限定符) )。

如何正确实现复制构造函数?

谢谢。

最佳答案

您的问题与复制构造函数没有直接关系。当我编译您的代码时,出现以下错误:

'Vector::X::get' : cannot convert 'this' pointer from 'const Vector' to 'Vector %'

这表明问题出在 const-ness 上,例如参见 this question及其接受的答案。

问题似乎在于,对于普通属性,get 访问器未声明为const。因此,您无法访问 const Vector^ 上的属性。

我认为解决方案是不使用简单的属性,而是自己实现两个访问器,使 get 访问器 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; }
    }

这种方法的问题在于,WinRT 类型中不能有 const 方法(我认为这就是为什么 get 访问器不是 const 在平凡的属性中)。因此,如果您将类型更改为 public ref class,您将收到此错误:

'get': 'const' and 'volatile' qualifiers on member functions of WinRT types are not supported

因此,我认为最好的选择是不在复制构造函数中使用 const:

Vector::Vector(Vector^ v)
{
    this->X = v->X;
    this->Y = v->Y;
}

尽管我不确定为什么您甚至需要 ref 类 的复制构造函数,因为您总是将其用作引用。

关于c++ - 如何在 C++/CX 中使用具有属性的类创建复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11599154/

相关文章:

xaml - 如何将 C++/CX 库添加到针对任何 CPU 的 Windows 应用商店解决方案

c++ - 为什么有一个基类会取消一个类被聚合的资格?

c++ - 覆盖 VCL 类/组件保护方法 - 如何编码和使用?

c++ - 在结构内部的 TR1 unordered_map 中定义哈希函数

windows-runtime - 将字典绑定(bind)到 WinRT 列表框

c# - FTP上传结束时不一定总能获得226 Transfer OK

C++ 指向函数的友元指针

c++ - 如何填充加权图的邻接表?

c++ - 库包含 WinRT 损坏

c++ - UWP C# 应用程序调用用 C++ 编写的 Windows 运行时组件