class Foo
{
public:
int bar; // member
Foo ( int bar ) : bar ( bar ) {} // constructor, initializes 'bar'
};
list <Foo> foolist ( 4, Foo(5) ); // foolist will contain 4 Foo objects with bar == 5
foolist.push_back( Foo(6) ); // adds a Foo object with bar == 6
#include<iostream>
#include<list>
usingnamespace std;
class date {
string n; //nume
float m; //media
public:
void set (string nume, float media) {
n = nume;
m = media;
}
void nume () {cout << n << '\xA';}
void media () {cout << m << '\xA';}
};
int main () {
list <date> s; list <date>::iterator it;
s.push_back(set ("Bob", 8.3));
it.begin().nume(); it.begin().media();
return 0;
}
class date {
string n; //nume
float m; //media
public:
date (string nume, float media) { // constructor - member function with the same name of the class and no return type -
n = nume;
m = media;
}
void nume () {cout << n << '\xA';}
void media () {cout << m << '\xA';}
};
int main () {
list <date> s;
s.push_back(date ("Bob", 8.3)); // call constructor
s.begin()->nume(); // s.begin() is an iterator
s.begin()->media();
return 0;
}
class date {
string n; //nume
float m; //media
public:
void set_values (string nume, float media) {
n = nume;
m = media;
}
};
int main () {
list <date> s;
date cache;
cache.set_values("Bob", 8.3);
s.push_back(cache);
return 0;
Or you use a variable, or you use a constructor. There are no other ways.
- Using the constructor makes you creating a temporary object of date -
Why don't you like the constructor?
If you change 'set_values' you can do this:
1 2 3 4 5 6 7
date &set_values (string nume, float media) {
n = nume;
m = media;
return *this;
}
//...
s.push_back( date().set_values("Bob", 8.3) ); // notice that 'date()' is the default constructor