我有这样的数据结构:
struct foo {
int id;
int route;
int backup_route;
int current_route;
}
以及一个名为update()的函数,用于请求对其进行更改.
update(42, dont_care, dont_care, new_route);
这真的很长,如果我在结构中添加一些内容,我必须在每次调用更新(...)时添加'dont_care'.
我正在考虑将结构传递给它,但事先用'dont_care'填充结构比在函数调用中拼写它更加繁琐.我可以使用默认值dont care在某处创建结构,并在我将其声明为局部变量后设置我关心的字段吗?
struct foo bar = { .id = 42, .current_route = new_route };
update(&bar);
将我希望表达的信息传递给更新功能的最优雅的方法是什么?
我希望其他一切都默认为-1("不关心"的密码)
使用C++ 11 std::array,我是否可以保证语法std::array<T, N> x;将默认初始化数组的所有元素?
编辑:如果没有,是否有一个语法可以在所有数组(包括零大小的数组)上工作,以将所有元素初始化为默认值?
编辑:在cppreference上,默认的构造函数描述说:
(constructor) (implicitly declared) (public member function)
default-constructs or copy-constructs every element of the array
Run Code Online (Sandbox Code Playgroud)
所以答案可能是肯定的.但我想根据标准或未来标准确定这一点.
是否可以在python中从字典创建一个对象,使每个键都是该对象的属性?
像这样的东西:
d = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee(d)
print e.name # Oscar
print e.age + 10 # 42
Run Code Online (Sandbox Code Playgroud)
我认为这几乎与这个问题相反:来自对象字段的Python字典
在内部和关于生成的代码,是否有真正的区别:
MyClass::MyClass(): _capacity(15), _data(NULL), _len(0)
{
}
Run Code Online (Sandbox Code Playgroud)
和
MyClass::MyClass()
{
_capacity=15;
_data=NULL;
_len=0
}
Run Code Online (Sandbox Code Playgroud)
谢谢...
我一直在写类似的东西
char *x=NULL;
Run Code Online (Sandbox Code Playgroud)
假设是
char *x=2;
Run Code Online (Sandbox Code Playgroud)
会创建一个char指向地址2 的指针.
但是,在GNU C编程教程中,它表示int *my_int_ptr = 2;将整数值存储2到my_int_ptr分配时的任何随机地址.
这似乎意味着我自己char *x=NULL正在将NULL一个cast 的值分配给char内存中的某个随机地址.
而
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *x=NULL;
if (x==NULL)
printf("is NULL\n");
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
事实上,印刷品
一片空白
当我编译并运行它时,我担心我依赖于未定义的行为,或者至少是指定不足的行为,我应该写
char *x;
x=NULL;
Run Code Online (Sandbox Code Playgroud)
代替.
可能重复:
C++初始化列表
在选项1和选项2中初始化变量的优缺点是什么?
class MyClass
{
public:
MyClass( float f, char a );
private:
float mFloat;
char mCharacter;
bool mBoolean;
int mInteger;
};
MyClass::MyClass( float f, char a ) : mFloat( f ), mBoolean( true ) // option 1.
{
// option 2
mCharacter = a;
mInteger = 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑:为什么选项2如此常见?
struct x {
char a[10];
char b[20];
int i;
char *c;
char *d[10];
};
Run Code Online (Sandbox Code Playgroud)
我正在填充此结构,然后使用值.在下一次迭代中,我想在重新开始重用之前0或null之前重置所有字段.
我怎样才能做到这一点?我可以使用memset或者必须通过所有成员然后单独进行吗?
以下代码(取自此处):
int* ptr = int();
Run Code Online (Sandbox Code Playgroud)
在Visual C++中编译并对指针进行值初始化.
怎么可能?我的意思是int()产生一个类型的对象,int我不能指定int一个指针.
上面的代码如何不违法?
考虑两个类:
class A {
var x: Int
init(x: Int) {
self.x = x
}
convenience init() {
self.init(x: 0)
}
}
class B: A {
init() {
super.init() // Error: Must call a designated initializer of the superclass 'A'
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么不允许这样做.最终,每个类的指定初始化叫他们需要的任何值,那么为什么我要重复我自己B的init通过指定一个默认值x再次,当方便init在A会做得很好?
initialization ×10
c ×3
c++ ×3
pointers ×2
arrays ×1
attributes ×1
c# ×1
c++11 ×1
class ×1
constructor ×1
dictionary ×1
properties ×1
python ×1
stdarray ×1
struct ×1
swift ×1
visual-c++ ×1