standard C++ come int o char avere ctors, in modo da poter avere espressioni come:Passando una variabile anonima per riferimento
tipiint a = int(67); // create anonymous variable and assing it to variable a
int b(13); // initialize variable b
int(77); // create anonymous variable
definito dall'utente (strutture o classi) sono in grado di fare lo stesso:
struct STRUCT
{
STRUCT(int a){}
};
STRUCT c = STRUCT(67);
STRUCT d(13);
STRUCT(77);
La domanda è: perché possiamo passare da una struttura anonima di riferimento o da istanze di classe, ma non possiamo passare i tipi standard?
struct STRUCT
{
STRUCT(int a){}
};
void func1(int& i){}
void func2(STRUCT& s){}
void func3(int i){}
void func4(STRUCT s){}
void main()
{
//func1(int(56)); // ERROR: C2664
func2(STRUCT(65)); // OK: anonymous object is created then assigned to a reference
func3(int(46)); // OK: anonymous int is created then assigned to a parameter
func4(STRUCT(12)); // OK: anonymous object is created then assigned to a parameter
}
La riga 'func2' non deve essere compilata (per lo stesso motivo della prima). – Mat
'void main()' non è standard. –
Con un livello di avviso appropriato, si otterrà l'avvertenza C4239: estensione non standard utilizzata: 'argomento': conversione da 'STRUCT' a 'STRUCT &'; Un riferimento non const può essere associato a un lvalue'. Dovresti usare '/ W4'. –