c++类默认属性

c++ Class default property

本文关键字:属性 默认 c++      更新时间:2023-10-16

c++中有没有办法将联合/类/结构中的属性设置为默认属性?我使用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人。b或

Board.by[3]=32;

以便在数组的字节3中放入32。我认为这是不可能的,但可能有人知道一种方法。谢谢


不错的解决方案!

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

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

但在这一行有一个错误:

if (someBitboard)

错误166错误C2451:条件表达式不是有效的

感谢

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

#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 Union:中

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

注意:请注意与值的内存布局(endianes)有关的平台依赖关系。

您可以重载=运算符:

class C
{
public:
    void operator = (int i)
    {
        printf("= operator called with value %dn", 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;
}