在我的大学脚本中写道,我们不允许在运行时创建一个只在运行时知道大小的本地数组。
float x [size] [2];
这不起作用,因为声明的数组不具有运行时大小。尝试一个矢量:
来自:C++ expected constant expression
但是,此代码在Apple LLVM 8.0.0下编译
#include <iostream>
int main(){
int i = 5;
int x;
std::cin >> x;
int array[x];
for(int i = 0; i<x; ++i){
std::cout << array[i] << "\n";
}
}
编辑:并且工作正常。按预期打印出垃圾。
提醒:这个程序无意义。
答案 0 :(得分:2)
此功能称为“可变长度数组”,是编译器扩展;它不是标准的一部分。
如果您使用public class Parent
{
public int ParentId {get; set;}
public string Name {get; set;}
public virtual ICollection<Child> Children {get; set;}
}
public class Child
{
public int ChildId {get; set;}
public string Name {get; set;}
// By convention will become the foreign key to Parent:
public int ParentId {get; set;}
public virtual Parent Parent {get; set;}
}
public class MyDbContext : DbContext
{
public DbSet<Parent> Parents {get; set;}
public DbSet<Child> Children {get; set;}
}
public void Main()
{
using (var dbContext = new MyDbContext(...))
{
var addedParent = dbContext.Parents.Add(new Parent()
{
Name = "Phil Dunphy",
}
// if you do not want to add a child now, you can SaveChanges
dbContext.SaveChanges();
// now addedParent has a ParentId, you can add a child:
var addedChild = dbContext.Children.Add(new Child()
{
Name = "Luke Dunphy",
ParentId = addedParent.Id,
};
dbContext.SaveChanges();
}
}
进行编译,Clang会向您发出此警告:
-pedantic
如果您的代码需要便携,请不要使用此功能。