每当我看到一个C"类"(通过访问将指针作为第一个参数的函数来使用的任何结构)时,我看到它们实现如下:
typedef struct
{
int member_a;
float member_b;
} CClass;
CClass* CClass_create();
void CClass_destroy(CClass *self);
void CClass_someFunction(CClass *self, ...);
...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,它CClass_create
始终malloc
是内存并返回指向它的指针.
每当我看到new
C++不必要地出现时,它似乎通常会让C++程序员疯狂,但这种做法在C中似乎是可以接受的.为什么堆分配的结构"类"如此常见?
我从这个网站下载了Clang 3.6.2,并尝试使用Windows下的Code :: Blocks进行设置.不幸的是,由于它不知道在哪里,它无法编译一个简单的"hello world"程序iostream
.
查看安装文件夹,它似乎没有包含标准库.为什么?我怎么得到它?
如果我有一个通用的struct/class:
template<typename T>
struct Container
{
T value;
Container(const Value& value) : value(value) { }
};
Run Code Online (Sandbox Code Playgroud)
我想对其中两个执行操作:
template<typename T, typename U>
Container<T> operator+(const Container<T>& lhs, const Container<U>& rhs)
{
return Container<T>(lhs.value + rhs.value);
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果lhs
是类型Container<int>
和rhs
类型Container<float>
,那么我会Container<int>
回来.但是,如果我这样做auto result = 2 + 2.0f
,那么result
就是那种类型float
.因此内置类型和自定义类型之间的行为不一致.
那么我将如何处理operator+
重载并使其返回Container<float>
,就像C++如何使用内置类型处理算术推广一样?
以lua的简单C函数为例:
int luacfunc(lua_State *L)
{
printf("%g\n", lua_tonumber(L, 1) + lua_tonumber(L, 2));
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,参数显示为索引1
和2
.由于正数表示堆栈自下而上,这意味着参数位于堆栈的底部,而不是顶部.
为什么会这样?它是否需要在每个函数调用上移动整个堆栈以为参数腾出空间?
鉴于此代码:
template<typename T>
struct Type
{
T value;
};
template<typename T>
Type<T> operator+(const Type<T>& type, T val)
{
Type<T> type;
type.value += val;
return type;
}
int main()
{
Type<float> type;
type = type + 2;
}
Run Code Online (Sandbox Code Playgroud)
我在MSVC中收到错误:
Error C2782 'Type<T> operator +(const Type<T> &,T)': template parameter 'T' is ambiguous
Error C2676 binary '+': 'Type<float>' does not define this operator or a conversion to a type acceptable to the predefined operator
Error no operator "+" matches these operands
Run Code Online (Sandbox Code Playgroud)
我认为它只会将int提升为浮点数,但显然它不想这样做.有办法解决这个问题吗?