How to set/get value in struct inside a struct - c++

How can i access my struct to get/set value inside of it??
Here my example code
#include <iostream>
using namespace std;
typedef struct t_TES
{
double dTes;
}TES;
struct SAMPLE1
{
struct TES;
};
int main()
{
SAMPLE1 sss;
//How can i get/set dtes value??
sss.TES.dtes=10;
cout<<sss.TES.dtes<<endl;
return 0;
}
Is it posible to assign value like this "sss.TES.dtes=10";
and get the value like by calling this "sss.TES.dtes";
i already try to combine both -> or :: operator to get/set value but always got an compilation error.
Pardon me for my bad english, Thanks..

structs in C++ don't need typedef or the struct keyword for instances, but they do need names for their members. Also, it's a case-sensitive language, so dtes is not the same as dTes. Try:
#include <iostream>
using namespace std;
struct TES
{
double dTes;
};
struct SAMPLE1
{
TES tes;
};
int main()
{
SAMPLE1 sss;
sss.tes.dTes = 10;
cout << sss.tes.dTes << endl;
return 0;
}

You have two problems with the SAMPLE1 structure: The first is that you use struct TES when TES is not actually a structure (it's an alias of a structure). The second problem is that you have to actually declare a member in the SAMPLE1 structure:
struct SAMPLE1
{
t_TES tes;
};
Then you just nest the use of the dot-operator . (like you do now):
SAMPLE1 sss;
sss.tes.dTes = 0.0;

You can't. With struct TES;, you are not declaring a member variable. Try e.g. TES member_name, then you can access it with sss.member_name in your main. Also, you should try to use more descriptive variable names ;-)

Related

Using a Struct within a Constructor

Using a constructor, can I set values to variables located in the classes private using information that would be stored in a struct vector? This would construct the values for the class, one of which being the string name of the month-monthName-using the numerical place of the month as a guide for the place in the struct vector.
//m/d/y;year_is_private_variable
Date(unsigned m, unsigned d, unsigned y){
year=y;
for(unsigned i=0;i<12;++i){
if(m==yVector.mPlace.at(i)){
monthName=yVector.mName.at(i);
}
}
You can use values stored by internal parts of class/structure to initialise other class/struct variables at construction time. But, you have to keep in mind that the variables which you want to use shall be initialised before usage.
For purposes of your example you can use static const field to store all the months. Simplified code below
#include <iostream>
#include <string>
#include <vector>
struct Date
{
Date(int month)
: month_name(values[month])
{
}
std::string month_name;
private:
static const std::vector<std::string> values;
};
const std::vector<std::string> Date::values = {"may", "april"};
int main()
{
Date d = Date(1);
std::cout << d.month_name;
return 0;
}

How can I declare a struct?

I am currently learning C++ and trying to understand the usage of structs.
in C++. As far as I'm aware, if you want to define a function after the main() function, you have to declare it beforehand, like in this function (Please tell me if I'm wrong with it):
#include "stdafx.h"
#include <iostream>
#include <string>
void printText(std::string); // <-- DECLARATION
int main()
{
std::string text = "This text gets printed.";
printText(text);
}
void printText(std::string text)
{
std::cout << text << std::endl;
}
My question now is if there is a way to do the same with structs. I don't want having to always define a struct before the main() function, just because I prefer it like that. However, I get an error when I try doing it like that:
//THIS program DOESN'T work.
#include "stdafx.h"
#include <iostream>
#include <string>
struct Products {std::string}; // <-- MY declaration which DOESN'T work
int main()
{
Products products;
products.product = "Apple";
std::cout << products.product << std::endl;
}
struct Products
{
std::string product;
};
When I delete the decleration and instead define the struct before the main function, the program works so I assume I'm somehow wrong with the decleration:
//THIS program DOES work
#include "stdafx.h"
#include <iostream>
#include <string>
struct Products
{
std::string product;
};
int main()
{
Products products;
products.product = "Apple";
std::cout << products.product << std::endl;
}
Could someone tell me if there is some way to declare a struct like that? Bear with me if I have any major mistake in the code, I'm just a beginner.
Thanks in advance!
You can pre-declare (forward-declare) a class type in C++.
struct Products;
However, a class type declared in this way is incomplete. Incomplete types can only be used in a number of very limited ways. You will be able to declare pointers or references to such type, you will be able to mention it in non-defining function declarations etc., but you will not be able to define objects of such incomplete type or access their members.
If you want to define objects of class Products or access members of class Products, you have no other choice but to fully define the class before such use.
In your case you are defining an object of type Products in main as well as accessing members of class Products there. This means that you have to completely define Products before main.
In your particular case a forward declaration wont help, because a forward declaration only allows you to use pointers or references, as e.g. in
struct foo;
foo* bar(foo f*) { return f;}
struct foo { int x; }
However,
struct Products {std::string};
is not a declaration, but if you want an ill-formed declaration and definition.
The correct forward declaration would be:
struct Products;

Cannot declare array of strings as class member

I could not declare an array of strings in my class. Below my class definition:
class myclass{
public:
int ima,imb,imc;
string luci_semaf[2]={"Rosso","Giallo","Verde"};
};
and my main file
#include <iostream>
#include <fstream>
#include "string.h"
#include <string>
using namespace std;
#include "mylib.h"
int main() {
return 0;
}
Why do I get the following warnings / error?
You have two problems: The first is that you can't initialize the array inline like that, you have to use a constructor initializer list. The second problem is that you attempt to initialize an array of two elements with three elements.
To initialize it do e.g.
class myclass{
public:
int ima,imb,imc;
std::array<std::string, 3> luci_semaf;
// Without C++11 support needed for `std::array`, use
// std::string luci_semaf[3];
// If the size might change during runtime use `std::vector` instead
myclass()
: ima(0), imb(0), imc(0), luci_semaf{{"Rosso","Giallo","Verde"}}
{}
};
You can not initialize data member.
You can write like this:
class myclass{
public:
myclass() {
luci_semaf[0] = "Rosso";
luci_semaf[1] = "Giallo";
luci_semaf[2] = "Verde";
}
private:
int ima,imb,imc;
string luci_semaf[3];
};
You can assign the values of the array in the Сonstructor
You're declaring an array of size 2 but providing 3 strings!
Try storing the elements in vector of strings, in c++ vectors are used more often.
class myclass{
public:
int ima,imb,imc;
std::vector<std::string> strings;
myclass() {
strings.push_back("blabla");
}
};

C++ compile time error: expected identifier before numeric constant

I have read other similar posts but I just don't understand what I've done wrong. I think my declaration of the vectors is correct. I even tried to declare without size but even that isn't working.What is wrong??
My code is:
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
using namespace std;
vector<string> v2(5, "null");
vector< vector<string> > v2d2(20,v2);
class Attribute //attribute and entropy calculation
{
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
public:
Attribute(){}
int total,T,F;
};
int main()
{
Attribute attributes;
return 0;
}
You cannot do this:
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
in a class outside of a method.
You can initialize the data members at the point of declaration, but not with () brackets:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
Before C++11, you need to declare them first, then initialize them e.g in a contructor
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
As an alternative you can use constructor initializer lists
Attribute():name(5), val(5, 0) {}
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}

(C/C++) struct initalization syntax

When I make my own struct, say:
struct myStruct{
int data1;
int data2;
string data3;
}
I can initialize an instance of type myStruct like this:
myStruct instance1;
So my question is, why am I often seeing "struct" written during the initialization of a struct?
Maybe that's an inaccurate statement so here is an example of what I mean:
/*This is a tiny program that checks
to see if a file exists in
the current working directory. */
#include <sys/stat.h>
#include <iostream>
using namespace std;
const string FILENAME = data.txt;
int main(){
struct stat fileStatus; //<-- HERE HERE HERE!
if (FileExists(FILENAME, fileStatus)){
cout << "File Does Exist" << endl;
}else{
cout << "File Does NOT Exist" << endl;
}
return 0;
}
bool FileExists(const string & fileName,struct stat & fileStatus){
bool fileDoesNotExist = stat (fileName.c_str(), &fileStatus);
return !fileDoesNotExist;
}
>
LINE 13: struct stat fileStatus;
Is this something that was done in C for some reason?
Something with a macro or a typedef?
I just don't understand why this is the way it is.
This is a C thing; there's no good reason to continue to do it in C++.1
In C, struct is part of the typename, e.g.:
struct foo { int x; };
defines a type called struct foo. In C++, it defines a type called foo. In C, you can usually hide this irritation behind a typedef:
typedef struct foo { int x; } foo;
1 At least, not in code that couldn't possibly also be compiled as C (such as the example in your question).
You can do what you want by instead calling it like this:
typedef struct mystruct
{
int itema;
int itemb;
Etc...
}* mystruct;
So that's whenever you make a mystruct item it creates a pointer to your struct, else you have to call your struct by
struct mystruct *object;