我有一个非常基本的问题。在C中,我们声明了如下结构:
片段1
struct node {
int a;
int b;
char c;
};
我理解结构背后的基本概念。它可以从多个角度看。它是一个“结构”,用于创建用户定义的类型。
除非我们为结构定义对象,否则结构是无用的。我们可以像这样为它创建对象:
struct node obj1;
obj1.a=10; // corresponds to the value of obj1
obj1.c='A'; // ....
and so on..
好的,下面的代码片段我无法理解。
片段2:
struct nod
我知道C& C++都是不同的语言,今天我在下面的程序中做了一个小错误,但是这个程序在各种C++编译器(g++、clang、MSVC++)上编译得很好。
考虑下列方案:
int main()
{
int s[]={3,6,9,12,18};
int* p=+s; // Observe this strange looking initialization due to use of unary + operator
}
上面的程序在C++中编译得很好(参见live ),但在C中编译却不是这样(参见live )。我的编译器( gcc 4.8.1 )在将它编译为C程序时给出
#include <stdio.h>
int main()
{
unsigned int a=10;
int b=10;
int c=-1;
printf("%d %d %d",(c%a),(c%(int)a),(c%b));
return 0;
}
输出“5-1-1”(使用)。到5点算什么?是否只是将无符号int转换为int正确的补丁,只要它适合于int?
我可以执行以下代码显示的操作:
std::string a = "chicken ";
std::string b = "nuggets";
std::string c = a + b;
然而,这是失败的:
std::string c = "chicken " + "nuggets";
它给了我一个错误,说“'+‘不能添加两个指针”。为什么是这样?有没有其他方法可以做到这一点而不出错呢?
根据节核心常量表达式( point 19),两个指针之间的减法运算符直到c++14才是合法的常量表达式。我是否可以假设以下代码是合法的c++17代码,或者这种解释是滥用的?
int X, Y;
template <long long V>
struct S { };
int main() {
S<&X - &Y> s;
(void)s;
}
这听起来可能很傻,我不知道。
class Example {
private:
Example x;
public:
//Methods
};
这在JAVA中是可能的,但在C++中却显示了错误。(字段“x”的类型不完整)
我如何在C++中做到这一点?如果不是的话,还有其他方法来做同样的事情。我知道一条,指点:)还有什么吗?
而且,我很乐意知道,在C++中,是什么限制了同样的操作。
谢谢。
我不确定这些代码是如何工作的。c0 =新的C();*是如何工作的?如何从'C‘生成指针'A’对象?
class A {
public:
A() { print("Constructor of A"); }
virtual ~A() { print("Destructor of A"); }
};
class B : public A {
public:
B() { print("Constructor of B"); }
~B() { print("Destructor of B"
我的代码在c和c++中的行为是不同的。
void *(*funcPtr)() = dlsym(some symbol..) ; // (1) works in c but not c++
int (*funcPtr)();
*(void**)(&funcPtr) = dlsym(some symbol..) ; // (2) works in c++
我不明白为什么第二次铸造工作在c++,而第一次铸造不工作在c++。在c++中,(1)显示的错误消息从void*到void*()的转换是无效的。
在C中,如果我有两种类型的指针:
typeB *q;
typeA *p;
在以下情况下,是否没有必要将显式强制转换(typeA *)
1 p= q is fine, no need to use p = (typeA *)q;
2 define: void func(typeA *p){}
call: func(q); is fine, no need to use func((typeA *)q)
3 p=malloc(sizeof(typeA)); is fine, no need to use p=(typeA *)mall
以下代码:
void f(const uint8_t* a) {} // <- this is an external library function
enum E : uint8_t { X, Y, Z };
int main(void) {
E e = X;
f(&e); // <- error here
}
产生以下错误:
/tmp/c.cc:10:3: error: no matching function for call to 'f'
f(&e);
^
/tmp/c.cc:5:6: note: candidate
下面的片段在Clang4.0中没有错误,但是GCC 7.0生成了 (注意-std=c++1z标志的使用)。
using FuncT = int (*)(double);
template <FuncT FUNC>
int temp_foo(double a)
{
return FUNC(a);
}
int foo(double a)
{
return 42;
}
void func()
{
auto lambda = [](double a) { return 5; };
struct MyStruct
{
stati