gpt4 book ai didi

c++ - 类 x 不存在默认构造函数,继承中的运算符

转载 作者:行者123 更新时间:2023-11-28 06:50:44 27 4
gpt4 key购买 nike

我试图实现 CUDA 博客上给出的统一虚拟内存示例: http://devblogs.nvidia.com/parallelforall/unified-memory-in-cuda-6/

Visual Studio 2013 给我一个错误:类“Term”不存在默认构造函数

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>
#include <iostream>

#define NUM_ATTRIBUTES 10

class Managed {
public:
void *operator new(size_t len) {
void *ptr;
cudaMallocManaged(&ptr, len);
std::cout << "custom new for size " << len << '\n';
return ptr;
}
void *operator new[] (size_t len) {
void *ptr;
cudaMallocManaged(&ptr, len);
std::cout << "custom new for size " << len << '\n';
return ptr;
}
void operator delete(void *ptr) {
cudaFree(ptr);
}
};

class Attribute : public Managed {
public:
int num_levels;
int num_active_levels;
int active_levels;
};

class Term : public Managed {
public:
int num_active_attributes;
int active_attributes;
Attribute attribute[NUM_ATTRIBUTES];

// Unified memory copy constructor allows pass-by-value
Term (const Term &orig) {
num_active_attributes = orig.num_active_attributes;
active_attributes = orig.active_attributes;
cudaMallocManaged((void **)&attribute,NUM_ATTRIBUTES * sizeof(Attribute));
memcpy(attribute, orig.attribute, NUM_ATTRIBUTES * sizeof(Attribute));
}
};

int main()
{
Term * A = new Term[10];
getchar();
return 0;
}

Term 类不是继承自父类 Managed 中定义的新运算符吗?

最佳答案

这与 CUDA 无关。编译器不会生成默认构造函数,因为您已经提供了另一个构造函数(拷贝)。

只需显式请求默认构造函数:

class Term : public Managed {
public:
...

// C++11
Term() = default;

// Pre C++11 alternative (although not strictly equivalent)
Term() {}
...
};

另请注意,operator new 和构造函数是两个不同的东西:new 用于分配 存储,构造函数用于初始化 将存储转换为有意义的状态(大致)。

关于c++ - 类 x 不存在默认构造函数,继承中的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23997028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com