What is the syntax to access members of a structure without
explicitly naming the structure in every access?
struct mytype {
int a;
char* b;
Its time to unlearn the lies:
member b is a pointer to a single character. char* b cannot store
anything else. Relying on a pointer to a single char to store an array
of characters
is doomed to fail. The compiler has not allocated or reserved memory
to store an array of
chars. You'ld have to store the null-terminated character sequence
using a
buffer (ie: char b[128]
.
However - there is a better solution: std::string (its dynamic and
packed with features).
long c;
} IT;
How can I access the structure members in a way similar to the old pascal
USING statement?
using IT (
a=5;
b="hello";
c=45l;
);
I cannot remember the c++ syntax to accomplish this.
Using a function or a constructor. IT is not a type/struct/class, its
an instance of mytype. Consider a primitive array:
mytype arr[100];
Which one of those 100 instances' member's did you want to modify? You
need to tell the program which one to act on. (ie: array[0].set(...)
But wait a minute, why set anything when you can allocate AND
initialize private members simultaneously at construction time?
#include <iostream>
#include <string>
struct mytype {
private:
int a;
std::string b;
long c;
public:
// default ctor + init list
mytype()
: a(0), b("default string"), c(0) { }
// parametized ctor + init list
mytype(const int n,
const std::string& s,
const long l)
: a(n), b(s), c(l) { }
// friend op<< for output
friend std:
stream& operator<<(std:
stream& os, const mytype& t)
{
os << "a = " << t.a;
os << "\nb = " << t.b;
os << "\nc = " << t.c;
return os;
}
};
int main()
{
mytype instance(5, "hello", 451); // done
std::cout << instance << std::endl;
mytype array[100];
std::cout << array[0] << std::endl;
}
// Note: all 100 instances in that array[] are already set.