In the code below, I don't seem to understand the limitations of the curly bracket initialisation. What do they actually do? It seems in the case of A it just sets a[0] equal to the value directly. In the case of b it using implicit conversion. Does it decide which one to do based on what is available, or is there some other method it uses?
#include <iostream>
using namespace std;
struct A
{
};
struct B
{
B(int a) { cout << a; }
};
int main()
{
A* a[] = {new A()};
B b[] = {1};
}
Also would this type of curly bracket initialisation work similarly in Java?
public class A
{
public static void main(String[] args)
{
someClass[] sC = { /* what can go here? an argument to the constructor,
or just a value to set the variable equal to */ }.
}
}
Sorry if my question seems silly, just really want to know more about curly brackets in c++ and Java. Thanks in advance :-开发者_运维百科)
Since the Java part has already been answered, I will add a bit about the C++ part. The specific version of curly brace initialization that you refer to is called aggregate initialization and (unsurprisingly) is used to initialize aggregates. Each element in the aggregate will be initialized with the corresponding element inside the braces and you can use whatever you want to use that can be implicitly convertible to the type of the element in the aggregate.
There are a couple of specific parts of the feature that you might want to consider for the specific case of arrays. The number of elements inside the curly braces cannot be greater than the size of the array, but it can be smaller in which case the rest of the elements will be default initialized.
int a[5] = { 1, 2 }; // [ 1, 2, 0, 0, 0 ]
If the size of the array is not provided in user code, the compiler will set it to the number of elements in the aggregate-initialization list:
int a[] = { 1, 2, 3 }; // int a[3]
Note that unlike in Java, the size is an integral part of the type of the array, so that while you can type int a[] = { 1 };
, it can never be a generic array of undetermined number of int
.
In C++11 the curly brace syntax has been extended to provide uniform initialization, but that is probably outside of the scope of the question, I just mention it in case you want to read more on the subject.
It's the same thing as in C++
someClass[] sC = { new someClass(), new someClass(), new someClass() };
int[] i = { 1, 2, 3 };
String[] s = { "1", "2", "3" };
I don't quite remember how it is done in C++, but in java you can do:
String[] array = new String[]{ "a", "b", "c" };
So you don't pass arguments to the constructors, you pass the objects themselves.
In Java, array is a container object.
You can store values for primitive types and object references of someClass
or its sub-classes
into array of someClass[] sC
.
class SomeClass {}
class Foo extends SomeClass{}
Foo f=new Foo();
SomeClass []sC={f,new Foo(),new SomeClass()};
精彩评论