我希望在以下结构中有一个命名联合,这样我就可以memcpy在不知道哪个字段是"活动"的情况下使用它.
struct Literal {
enum class Type : size_t {
INT = 1,
LONG,
FLOAT,
DOUBLE
} type;
union {
int li;
long ll;
float lf;
double ld;
} v;
constexpr Literal(int li): type{Type::INT}, v.li{li} {}
constexpr Literal(long ll): type{Type::LONG}, v.ll{ll} {}
constexpr Literal(float lf): type{Type::FLOAT}, v.lf{lf} {}
constexpr Literal(double ld): type{Type::DOUBLE}, v.ld{ld} {}
};
Run Code Online (Sandbox Code Playgroud)
如何初始化构造函数中的字段?既没有v.li{li}也没有li{li}工作.
我也试过,v{li}但它只适用于第一个构造函数,因为它将其他3个转换为int.
编辑:来自@StoryTeller的回答和评论:
struct Literal {
enum class Type : size_t {
INT = 1,
LONG,
FLOAT, …Run Code Online (Sandbox Code Playgroud) 使用随机值使用 JUnit 创建测试对象是一个好习惯吗?像这样 :
public class MonomialTest {
private static final Random RANDOM = new Random();
private Monomial monomial;
private float coefficient;
private int exponent;
@Before
public void setUp() throws Exception {
coefficient = RANDOM.nextFloat();
exponent = RANDOM.nextInt();
monomial = new Monomial(coefficient, exponent);
}
@Test
...
...
...
}
Run Code Online (Sandbox Code Playgroud)
还是应该使用固定值?
我必须编写一个函数来从链表中删除一个元素(我的,而不是集合框架的元素),所以这是我的第一次尝试:
public void remove(E element) {
Cell<E> cell = sentinel;
int i = 0;
while (i < count) {
if (cell.getElement().equals(element)) {
cell.getPrevious().setNext(cell.getNext());
--count;
return;
}
++i;
cell = cell.getNext();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:使用return这样的好吗?更一般地说,当检查条件并且没有指示运行以下指令时,我使用以下内容是有意义的return:
void func() {
while (condition) {
if (something) {
instructions;
return;
}
more instructions;
}
}
Run Code Online (Sandbox Code Playgroud)
但由于它不是非常易读,并且每个人都说可读性是java的优先考虑因素,我不得不考虑另一种方法.所以我改变了条件并使用了另外一个布尔值.
public void remove(E element) {
boolean found = false;
Cell<E> cell = sentinel;
int i = 0;
while (!found && i < count) {
if (cell.getElement().equals(element)) …Run Code Online (Sandbox Code Playgroud) 为什么java不允许访问父包中的包限制类型?
有类似的东西:
Package a
|--Class A
|--Package b
|--Class B
Run Code Online (Sandbox Code Playgroud)
如果类具有包可见性,则无法A从类访问类.我觉得这很有道理,但显然不是.BA
这是什么原因?