关于Scott Meyers的"Effective C++"中的第48项,我有一个简短的问题.我只是不明白从下面的书中复制的代码,
#include <iostream>
using namespace std;
template <unsigned n>
struct Factorial
{
enum { value=n*Factorial<n-1>::value };
};
template <>
struct Factorial<0>
{
enum { value=1};
};
int main()
{
cout<<Factorial<5>::value<<endl;
cout<<Factorial<10>::value<<endl;
}
Run Code Online (Sandbox Code Playgroud)
为什么我必须在模板编程中使用枚举?有没有其他方法可以做到这一点?我在这里先向您的帮助表示感谢.
我对书中的问题13.9提出了一个问题,即"破解编码面试".问题是编写一个支持分配内存的对齐alloc和free函数,在答案中代码如下:
void *aligned_malloc(size_t required_bytes, size_t alignment) {
void *p1;
void **p2;
int offset=alignment-1+sizeof?void*);
if((p1=(void*)malloc(required_bytes+offset))==NULL)
return NULL;
p2=(void**)(((size_t)(p1)+offset)&~(alignment-1)); //line 5
p2[-1]=p1; //line 6
return p2;
}
Run Code Online (Sandbox Code Playgroud)
我对第5行和第6行很困惑.为什么你必须做一个"和"因为你已经为p1添加了偏移?[-1]是什么意思?我在这里先向您的帮助表示感谢.
我对书中的这段代码很困惑:
typedef int (*healthCalcFunc) (const GameCharacter&)
Run Code Online (Sandbox Code Playgroud)
我明白,这
typedef double* PDouble意味着这个词PDouble可以用来声明一个指针double.
但我无法弄清楚其含义 typedef int (*healthCalcFunc) (const GameCharacter&)
有人能帮我解释一下吗?
提前致谢
:)
很抱歉再次打扰你们,但我有一个问题,我几天都没想出来.它是关于一个treap的旋转,例如,在pos处向右旋转一个treap.现在的问题是如何链接(或连接)pos->left到pos的原始父?我发现这个代码在线,有效,但我没有看到它如何解决我的问题,是因为使用*&?如果是这样,你能帮我解释一下吗?pos=b这段代码的功能是什么?
void Treap::right_rotate(Node *&pos) {
Node *b = pos->left;
pos->left = b->right;
b->right = pos;
pos = b;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!!
我在"UNIX NETWORK PROGRAMMING"一书中对这个结构的定义提出了一个问题(v2,pg162)这里是:
struct {
pthread_mutex_t mutex
int buff[MAXNITEMS];
int nput;
int nval;
} shared= {
PTHREAD_MUTEX_INTIALIZER
};
Run Code Online (Sandbox Code Playgroud)
共享后我无法理解代码.它到底意味着什么?提前致谢
我试图从文件中读取名称和密码到c中的结构,但显然我的代码不能按预期工作.有没有人可以帮我解决下面附带代码的问题?非常感谢!(基本上该文件有几个名称和密码,我想将它们读入结构帐户[]`)
#include <stdio.h>
#include <stdlib.h>
struct account {
char *id;
char *password;
};
static struct account accounts[10];
void read_file(struct account accounts[])
{
FILE *fp;
int i=0; // count how many lines are in the file
int c;
fp=fopen("name_pass.txt", "r");
while(!feof(fp)) {
c=fgetc(fp);
if(c=='\n')
++i;
}
int j=0;
// read each line and put into accounts
while(j!=i-1) {
fscanf(fp, "%s %s", accounts[j].id, accounts[j].password);
++j;
}
}
int main()
{
read_file(accounts);
// check if it works or not
printf("%s, %s, %s, %s\n", …Run Code Online (Sandbox Code Playgroud)