【发布时间】:2021-05-26 21:57:38
【问题描述】:
这个问题是Why is alloca returning the same address twice? 的后续问题。我找到了一种使用数组为两个实例获取不同内存地址的方法。
vml.h
#pragma once
#include <iostream>
namespace vml {
// Vectors
template <typename in_type, const int in_length>
class vec {
public:
vec(in_type* in_data) {
std::cout << data << std::endl;
std::copy(in_data, in_data + in_length, data);
}
vec() {
data = nullptr;
}
in_type& operator()(int index) const {
_ASSERT(0 <= index && index < in_length);
return data[index];
}
private:
in_type data[in_length];
};
main.cpp
#include <memory>
#include "vml.h"
int main() {
int list[] = { 1,2,3 };
int list2[] = {2,4,6 };
vml::vec<int, 3> a(list);
vml::vec<int, 3> b(list);
a(1) = 3;
return 0;
}
但是,当我运行代码时出现错误
Error C2440 'return': cannot convert from 'const in_type' to 'in_type &'
由于返回值是'data[index]',这一定意味着它是常数,但是,我没有将它定义为常数,为什么会发生这种情况?
【问题讨论】:
标签: c++ class constants overloading