C++ use iostream inside class [duplicate] - c++

This question already has an answer here:
Does not name a type
(1 answer)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I'm using iostream and map. When I try to set the functions, they throw an error.
My code:
#include "string"
#include "iostream"
#include "map"
using namespace std;
class myClass {
map<string, string> Map;
Map["Ziv"] = "Sion";
cout << Map["Ziv"];
};
My error:
error: 'Map' does not name a type
error: 'cout' does not name a type
Why I can't use iostream and cout?

Why I can't use iostream and cout?
Because a class cannot (directly) contain expression statements. It can contain only member declarations.
Expression statements can only be within functions. This would be correct for example:
class main {
map<string, string> Map;
void example_function() {
Map["Ziv"] = "Sion";
cout << Map["Ziv"];
}
};

you can't have a C++ progran without the main function so please create int main(){}. And change the double quotes in the #include directives to angle brackets like below:
#include <string>
#include <iostream>
#include <map>
using namespace std;
class myClass {
public:
int myFunc();
};
myClass :: int myFunc(){
map<string, string> Map;
Map["Ziv"] = "Sion";
cout << Map["Ziv"];
}
int main(){
myClass myclass;
myclass.myFunc();
return 0;
}
Please consider i am a beginner and forgive my mistakes if any.

In object oriented languages, like C++, you can't write expressions/statements in a class. You may want to use a function. Example:
#include<iostream>
using std::cout;
class Example {
public:
void sayHello() {
cout << "Hello!";
}
}
int main() {
new Example().sayHello(); // Prints Hello!
}

You have to enter the cout in a function, inside the class you can't execute functions, you just can describe them or variables / objects.

Class is an Entity which contains related data members and the operations to modify or access those data members. No expression can be executed within the class. It does not make an sense to do something that you can not access. Because the only way to access and modify something are operations.
Yes in case if you want to print something when the class object is created, you can do that in Constructor. May be this is what you want to do:
#include <map>
#include <iostream>
#include <string>
class myClass {
private:
std::map<std::string, std::string> Map;
public:
myClass(const std::string& key, const std::string& value){
Map[key] = value;
std::cout << value;
}
};
int main(){
myClass cls("Ziv", "Sion");
}

Related

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;

Can we initialize object with double quotation

Is it possible to do something like
Class obj="";
Can use "" to initialize an object? I saw this in an interview, and the interviewer mentioned it is valid.
Update:
Thanks for the answers here. For the benefit of future readers, I did some search, this is called copy constructor. Some links like
copy constructor parameters
could be useful.
Yes, it really is valid. Here is an example code where it works:
#include <iostream>
#include <string>
using namespace std;
class Class {
private:
string data;
public:
Class (const char* foo) {
data = foo;
}
};
int main()
{
Class foo="bar";
return 0;
}

C++ Pass an object into another object?

I don't know if I've missed something, but I can't seem to figure out how to make this work, and couldn't find the answer online.
Lets say I have a two classes, Class A, and Class B. (stored in separate files)
Class A has a function setName() that sets a variable within a Class A object.
Class B has a function setOtherName() that sets the value of a Class A object's name.
So I set setOtherName() up like so:
void setOtherName(ClassA& cla)
{
*cla.setName("foobar");
}
then my main script looks like so:
Class A burger;
Class B fries;
fries.setOtherName(*burger);
this does not work in my orignal script, I get the following error:
error: no matching function for call to 'ClassB::setOtherName(ClassA*&)
Any help is aprreciated! ( sorry for any confusion )
Actual code:
main.cpp:
#include <iostream>
#include "quests.h"
#include "player.h"
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
quests GameQuests;
player Player;
GameQuests.quest1(Player);
Player.main();
return 0;
}
quests.cpp:
#include "quests.h"
#include "player.h"
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void quests::quest1(player& charact){
cout << "By the way, what was your name?" << endl;
person1=4;
system("pause");
charact->setName();
}
The implementation of your setOtherName function should have the signature
void ClassB::setOtherName(ClassA& cla)
You need to specify that it is included in ClassB. Within your class definition of ClassB, make sure to include
void setOtherName(ClassA&);
Furthermore, since your variable burger is of type ClassA and not of type ClassA*, there is no need to dereference the variable upon passing it into the function. Call it like
fries.setOtherName(burger);
You have also incorrectly dereferenced the variable cla. That object is passed by reference, not pointer, so there is no need to dereference.
You have to read about pointers and reference mate.
This is how your function should look like
void setOtherName(ClassA& cla)
{
cla.setName("foobar");
}
There is no need to deference something that is not a pointer.
ClassA burger;
ClassB fries;
fries.setOtherName(burger);
again, you don't need to dereference burger since its not a pointer.
If burger was created like this:
ClassA* burger = new ClassA();
and the function
void setOtherName(ClassA& cla)
was taking a reference, you had to dereference burger
fries.setOtherName(*burger);
Why are you derefrencing burger? You told the compiler to expect class A by reference, not by pointer.
Try:
fries.setOtherName(burger);
Also, get rid of the asterisk on setOtherName.
void setOtherName(ClassA & cla)
{
cla.setName("foobar");
}
EDIT:
Wrote a sample program of what I think you are trying to do below.
#include <iostream>
#include <string>
class Burger
{
public:
Burger(){}
void setName(std::string name){ m_name = name; }
std::string getName(){ return m_name; }
private:
std::string m_name;
};
class Fries
{
public:
Fries(){}
void setOtherName(Burger & burger){ burger.setName("FryBurger"); }
private:
};
int main()
{
Burger A;
Fries B;
B.setOtherName(A);
std::cout << A.getName() << std::endl;
return 0;
}

How Do I Store Objects in a Object in a Vector? (C++)

I hope this is not a stupid question. Basically I would like to access a string stored in a Class (Statement is the name I am using) in a vector of type Statement. Basically I am trying to store objects in a dynamic hierarchy of objects.
Types.cpp:
#include<iostream>
#include<fstream>
#include <string>
#include <vector>
using namespace std;
class Statement{
public:
vector<string> Inner_String;
vector<Statement> Inner_Statement;
string contents;
void set_contents (string);
string get_contents(){ return contents;}
void new_string(string);
string get_string(int v){return Inner_String[v];}
void new_Inner_Statement(Statement);
Statement get_Inner_Statement(int v){return Inner_Statement[v];}
};
void Statement::set_contents(string s){
contents = s;
}
void Statement::new_string(string s){
Inner_String.push_back(s);
}
void Statement::new_Inner_Statement(Statement s){
Inner_Statement.push_back(s);
}
Main method:
#include <iostream>
#include "FileIO.h"
#include "Types.h"
using namespace std;
int main()
{
Statement test;
test.new_Inner_Statement(Statement());
Statement a = test.get_Inner_Statement(0);
a.set_contents("words");
cout << a.get_contents();
test.get_Inner_Statement(0).set_contents("string");
cout << test.get_Inner_Statement(0).get_contents();
return 0;
}
What happens is
cout << a.get_contents()
returns its string while
cout << test.get_Inner_Statement(0).get_contents()
does not.
Look at this piece of code:
test.get_Inner_Statement(0).set_contents("string");
^^^^^^^^^^^^^^^^^^^^^^^^^^^
It calls this function:
Statement get_Inner_Statement(int v)
which returns a copy object (temporary) of type statement. On this object, you calls set_contents function, at which cease to exists at the end of the call.
Then, you call:
test.get_Inner_Statement(0).get_contents();
that creates a new temporary, from the unchanged statement, and try to get its contents.

C++ Simple Variant Boost

I'm attempting to create a list of objects using the variant boost.
#include <string>
#include <list>
#include <iostream>
#include <boost/variant.hpp>
using namespace std;
using namespace boost;
class CSquare;
class CRectangle {
public:
CRectangle();
};
class CSquare {
public:
CSquare();
};
int main()
{ typedef variant<CRectangle,CSquare, bool, int, string> object;
list<object> List;
List.push_back("Hello World!");
List.push_back(7);
List.push_back(true);
List.push_back(new CSquare());
List.push_back(new CRectangle ());
cout << "List Size is: " << List.size() << endl;
return 0;
}
Unfortunately, the following error is produced:
/tmp/ccxKh9lz.o: In function `main':
testing.C:(.text+0x170): undefined reference to `CSquare::CSquare()'
testing.C:(.text+0x203): undefined reference to `CRectangle::CRectangle()'
collect2: ld returned 1 exit status
I realise that everything would be fine if i used the form:
CSquare x;
CRectangle y;
List.push_back("Hello World!");
List.push_back(7);
List.push_back(true);
List.push_back(x);
List.push_back(y);
But i would like to avoid that form if at all possible, since i would like to keep my objects unnamed. This is an important requirement for my system - is there any way i can avoid using named objects?
Just need to change a few things and it works:
#include <iostream>
#include <list>
#include <string>
#include <boost/variant.hpp>
using namespace std;
using namespace boost;
class CRectangle
{
public:
CRectangle() {}
};
class CSquare
{
public:
CSquare() {}
};
int main()
{
typedef variant<CRectangle, CSquare, bool, int, string> object;
list<object> List;
List.push_back(string("Hello World!"));
List.push_back(7);
List.push_back(true);
List.push_back(CSquare());
List.push_back(CRectangle());
cout << "List Size is: " << List.size() << endl;
return 0;
}
Specifically, you needed to define the CRectangle and CSquare constructors (that's why you were getting a linker error) and to use CSquare() rather than new CSquare() etc. Also, "Hello World!" has type const char *, so you need to write string("Hello World!") when passing it to push_back or it will get implicitly converted to bool here (not what you want).
Instead of List.push_back(new CSquare()); just write
List.push_back(CSquare());
And also write defination of your constructor
You forget to implement the constructors CRectangle::CRectangle() and CSquare::CSquare().
Either implement them somewhere outside the class such as:
CRectangle::CRectangle()
{
// :::
};
... or implement them inside the class:
class CRectangle {
public:
CRectangle()
{
// :::
}
};
... or remove the constructor declarations altogether:
class CRectangle {
public:
};