相关疑难解决方法(0)

阻止调用类中的数组的默认构造函数

在编写一个偏移数组类时(你的idxs从100开始变为1000,所以你创建的类考虑到了这一点而不浪费数组中的前100个插槽)我遇到了一个问题.
如何初始化一个具有C数组元素的类(问题是T没有def构造函数).基本上我希望阵列完全不受限制.例:

class MyClass
{
    MyClass(int i)
    {

    }
};
template <typename T, size_t n, size_t offset>
struct offsetedIdxArray
{
    T data[n];// error line : error C2512: 'MyClass' : no appropriate default constructor available
    offsetedIdxArray()
    {

    }
    T& operator [](size_t pos)
    {
        return data[(pos-offset)];
    }

};
Run Code Online (Sandbox Code Playgroud)

用法:

offsetedIdxArray<MyClass, 1024,offset> oia;
Run Code Online (Sandbox Code Playgroud)

使用def构造函数不是选项,因为我使用的类实际上是库类.

*编辑:* 与此处描述的问题无关,但事实证明我的宝贵的库类没有复制ctor,只需移动ctor,所以我不得不使用unique_ptr的向量.

c++ arrays initialization

2
推荐指数
1
解决办法
563
查看次数

联合会始终具有默认值为零吗?

请让我们考虑以下代码:

#include <iostream>
using namespace std;

union{
 int i;
}u;

int main(){

     int k=5;
     cout<<k+u.i<<endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

该代码向我显示输出5,这对我来说意味着,联合结构中的变量i具有默认值= 0,但是ideone.com上的同一代码显示了这样的警告

prog.cpp:6: warning: non-local variable ‘<anonymous union> u’ uses anonymous type and then prints  5 as well, and last one  core of this problem comes  from algorithm calculate  
Run Code Online (Sandbox Code Playgroud)

平方根的倒数,这里是代码

#include<iostream>
#include<math.h>
using namespace std;

float invsqrt(float x){

    float xhalf=0.5f*x;

    union{
         float x;
         int i;
    }u;

   u.x=x;
   u.i=0x5f3759df-(u.i>>1);
   x=u.x*(1.5f-xhalf*u.x*u.x);

   return x;
}

int main(){

    float  x=234;
    cout<<invsqrt(x)<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它也向我显示了输出,但是我的问题是,这段代码是否好?我的意思是因为int我没有进行最后处理,所以任何编译器都可以认为它的值为零吗?我的问题不清楚我说的是我不是英语为母语的人。

c++

1
推荐指数
1
解决办法
3504
查看次数

标签 统计

c++ ×2

arrays ×1

initialization ×1