c ++类默认属性

时间:2014-04-29 07:07:02

标签: c++ class visual-c++ properties

在c ++中是否有办法将union / class / struct中的属性设置为默认属性?我使用Visual Studio。 我们的想法是能够访问它们而无需引用它们。类似的东西:

typedef uint64_t tBitboard;

union Bitboard {
    tBitboard b;  //modifier somewhere in this line to set as default
    uint8_t by[8];
};

Bitboard Board;

然后我想访问:

Board=100;

将100放在Board.b中 或

Board.by[3]=32;

所以将32放在数组的字节3中。我认为这是不可能的,但也许有人知道一种方式。 谢谢!


很好的解决方案!

我正在尝试使用这个:     union Bitboard {         tBitboard b;         std :: uint8_t by [8];

    Bitboard(tBitboard value = 0) { b = value; }
    Bitboard& operator = (tBitboard value) { b = value; return *this;     }
};

但是在这一行中有一个错误:

if (someBitboard)

错误166错误C2451:条件表达式无效

由于

2 个答案:

答案 0 :(得分:1)

您可以向union添加构造函数和运算符:

#include <iostream>
#include <iomanip>

typedef std::uint64_t tBitboard;

union Bitboard {
    tBitboard b;
    std::uint8_t by[8];

    Bitboard(tBitboard value = 0) { b = value; }
    Bitboard& operator = (tBitboard value) { b = value; return *this; }
    std::uint8_t& operator [] (unsigned i) { return by[i]; }
};

int main()
{
    // Construct
    Bitboard Board = 1;
    // Assignment
    Board = tBitboard(-1);
    // Element Access
    Board[0] = 0;

    // Display
    unsigned i = 8;
    std::cout.fill('0');
    while(i--)
        std::cout << std::hex << std::setw(2) << (unsigned)Board[i];
    std::cout << '\n';
    return 0;
}

这包括在9.5联盟中:

A union can have member functions (including constructors and destructors), but not virtual (10.3) functions.

注意:请注意有关值的内存布局(endianess)的平台依赖性。

答案 1 :(得分:0)

您可以重载=运算符:

class C
{
public:
    void operator = (int i)
    {
        printf("= operator called with value %d\n", i);
    }
};

int main(int argc, char * argv[])
{
    C c;
    c = 20;

    getchar();
}

在重载具有某些默认行为的运算符时要小心。你可能更容易使用你的课程,但更难以让别人赶上你的习惯。使用位移运算符 - 如Bgie建议的那样 - 在这里会更好。

如果您发布数组,则可以自由访问其元素:

class C
{
public:
    int b[5];
};

int main(int argc, char * argv[])
{
    C c;
    c.b[2] = 32;
}