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;
}
Related
I am working through this problem I found on Git to brush up on some skills. Using friend is prohibited. C++ styling should be used compared to C.
Essentially, I cannot call the identify() function that belongs to the Brain member variable in my Human class. It just will not let me access it. If you can code this up, and explain where I am going wrong, that would be great.
Create a Brain class, with whatever you think befits a brain. It will have an Identify() function that returns a string containing the brain's address in memory, in hex format, prefixed by 0x.
Then, make a Human class, that has a constant Brain attribute with the same lifetime. It has an identify() function, that just calls the identity() function of its Brain and returns its result.
Now, make it so this code compiles and displays two identical addresses:
int main(){
Human bob;
std::cout << bob.identify() << "\n";
std::cout << bob.getBrain().identify() << "\n";
}
Here is what I have so far:
#pragma once
#include "Brain.h"
class Human
{
const Brain humanBrain;
public:
Human();
std::string identify();
};
#include "Human.h"
#include <iostream>
#include <string>
#include <sstream>
Human::Human()
{
this->humanBrain = new Brain;
}
std::string Human::identify()
{
Brain b = this->humanBrain.identify(); // This is essentially what I am trying to call--and I can't access it.
const Brain * ptr = humanBrain;
std::ostringstream test;
test << ptr;
return test.str();
}
#pragma once
#include <string>
#include <iostream>
class Brain
{
int age;
std::string gender;
void* ptr;
public:
Brain();
//std::string getBrain();
const std::string identify();
void setPtr(void* p);
};
#include "Brain.h"
#include <iostream>
#include <sstream>
Brain::Brain()
{
age = 10;
gender = "male";
}
const std::string Brain::identify()
{
//const Brain* bPtr = &this;
const Brain* bPtr = this;
ptr = this;
std::ostringstream test;
test << &bPtr;
std::string output = "Brain Identify: 0x" + test.str();
return output;
}
Your Human::humanBrain member is declared as type const Brain, which is correct per the instructions, however your Brain::identify() method is not qualified as const, so you can't call it on any const Brain object. This is the root of the problem that you are having trouble with.
In addition, there are many other problems with your code, as well:
Human::humanBrain is not a pointer, so using new to construct it is wrong. And, you don't need a pointer to get the address of a variable anyway. Nor do you actually need a pointer to the member at all in this project.
Human lacks a getBrain() method, so bob.getBrain() in main() will not compile, per the instructions.
Human::identify() is calling humanBrain.identify(), which returns a std::string as it should, but is then assigning that string to a local Brain variable, which is wrong (not to mention, you are not even using that variable for anything afterwards). The instructions clearly state that Human::identity() should simply call Brain::identify() and return its result, but you are not doing that.
Brain::identify() is printing the address of its local variable bPtr rather than printing the address of the Brain object that identify() is begin called on, per the instructions.
With all of that said, try something more like this instead:
Human.h
#pragma once
#include "Brain.h"
#include <string>
class Human
{
const Brain humanBrain;
public:
Human() = default;
std::string identify() const;
const Brain& getBrain() const;
};
Human.cpp
#include "Human.h"
std::string Human::identify() const
{
return humanBrain.identity();
}
const Brain& Human::getBrain() const
{
return humanBrain;
}
Brain.h
#pragma once
#include <string>
class Brain
{
int age;
std::string gender;
public:
Brain();
std::string identify() const;
};
Brain.cpp
#include "Brain.h"
#include <sstream>
Brain::Brain()
{
age = 10;
gender = "male";
}
std::string Brain::identify() const
{
std::ostringstream test;
test << "Brain Identify: 0x" << this;
return test.str();
}
Below is code for a simple book list with a class to store book names and isbn numbers into an overloaded function using a vector. This program runs fine and I can test it by returning a specific name (or isbn) using an accessor function from my class.
Question: I tried calling (instantiating?) a constructor with parameters from my class but it would not work, so I commented it out. Yet I was still able to run the program without error. From my main below - //BookData bkDataObj(bookName, isbn);
From watching tutorials, I thought I always had to make an object for a specific constructor from a class that I needed to call? My program definitely still uses my overloaded constructor and function declaration BookData(string, int); without making an object for it in main first.
Thanks for any help or input on this matter.
Main
#include <iostream>
#include <string>
#include <vector>
#include "BookData.h"
using namespace std;
int main()
{
string bookName[] = { "Neuromancer", "The Expanse", "Do Androids Dream of Electric Sheep?", "DUNE" };
int isbn[] = { 345404475, 441569595, 316129089, 441172717 };
//BookData bkDataObj(bookName, isbn); //how did program run without instantiating object for class?
vector <BookData> bookDataArr;
int arrayLength = sizeof(bookName) / sizeof(string);
for (int i = 0; i < arrayLength; i++) {
bookDataArr.push_back(BookData(bookName[i], isbn[i]));
}
cout << "Book 4 is: " << bookDataArr[3].getBookNameCl(); //test if works
return 0;
}
BookData.h
#include <iostream>
#include <string>
using namespace std;
class BookData
{
public:
BookData();
BookData(string, int); //wasn't I supposed to make an object for this constructor in my main?
string getBookNameCl();
int getIsbnCl();
private:
string bookNameCl;
int isbnCl;
};
BookData.cpp
#include "BookData.h"
BookData::BookData() {
bookNameCl = " ";
isbnCl = 0;
}
BookData::BookData(string bookNameOL, int isbnOL) { //how did I use this function
bookNameCl = bookNameOL; //definition without an object in main?
isbnCl = isbnOL;
}
string BookData::getBookNameCl() { //can still return a book name
return bookNameCl;
}
int BookData::getIsbnCl() {
return isbnCl;
}
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");
}
I need help with passing a function pointer on C++. I can't linkage one function for a class to other function. I will explain. Anyway I will put a code resume of my program, it is much larger than the code expose here but for more easier I put only the part I need to it works fine.
I have one class (MainSystem) and inside I have an object pointer to the other class (ComCamera). The last class is a SocketServer, and I want when the socket received any data, it sends to the linkage function to MainSystem.
ComCamera is a resource Shared with more class and I need to associate the functions ComCamera::vRecvData to a MainSystem::vRecvData or other function of other class for the call when receive data and send de data to the function class associate.
Can Anyone help to me?
EDDITED - SOLUTION BELOW
main.cpp
#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <exception>
#include <unistd.h>
using std::string;
class ComCamera {
public:
std::function<void(int, std::string)> vRecvData;
void vLinkRecvFunction(std::function<void(int, std::string)> vCallBack) {
this->vRecvData = vCallBack;
}
void vCallFromCamera() {
this->vRecvData(4, "Example");
};
};
class MainSystem {
private:
ComCamera *xComCamera;
public:
MainSystem(ComCamera *xComCamera) {
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iChannelNumber, std::string sData) {vRecvData(iChannelNumber, sData); });
}
void vRecvData(int iNumber, string sData) {
std::cout << "RECV Data From Camera(" + std::to_string(iNumber) + "): " << sData << std::endl;
};
};
int main(void) {
ComCamera xComCamera;
MainSystem xMainSystem(&xComCamera);
xComCamera.vCallFromCamera();
return 0;
}
Output will be:
MainSystem RECV Data From Camera(4): Example
You can have ComCamera::vRecvData be of type std::function<void(int, std::string)> and then have ComCamera::vLinkRecvFunction() be like this:
void ComCamera::vLinkRecvFunction(std::function<void(int, std::string)> callBack)
{
this->vRecvData = callBack;
}
and have MainSystem constructor be like this:
MainSystem::MainSystem(ComCamera *xComCamera)
{
using namespace std::placeholders;
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iNumber, std::string sData){vRecvData(number, sData);});
}
Still though the original question has way too much code to go through friend.
Here what you want :
#include<iostream>
using std::cout;
class A; //forward declare A
class B{
public:
void (A::*ptr)(int x); //Only declare the pointer because A is not yet defined.
};
class A{
public:
void increase_by(int x){
a+=x;
} // this function will be pointed by B's ptr
int a = 0; // assume some data in a;
B b; // creating B inside of A;
void analyze(int y){
(*this.*(b.ptr))(y);
} // Some function that analyzes the data of A or B; Here this just increments A::a through B's ptr
};
int main(){
A a; // creates A
cout<<a.a<<"\n"; // shows initial value of a
a.b.ptr = &A::increase_by; // defines the ptr that lies inside of b which inturns lies inside a
a.analyze(3); // calls the initialize method
(a.*(a.b.ptr))(3); // directly calls b.ptr to change a.a
cout<<a.a; // shows the value after analyzing
return 0;
}
Output will be :
0
6
I still don't get why would you do something like this. But maybe this is what you wanted as per your comments.
To know more read this wonderful PDF.
I am using inheritance for my code. ChangeRequest is my base class. The code is as follows.
ChangeRequest.h
#include <iostream>
#include <string>
using namespace std;
class ChangeRequest
{
int swapDay;
int newDay;
public:
void setSwapDay(int newDay);
int getSwapDay();
void setNewDay(int newDay);
int getNewDay();
};
ChangeRequest.cpp
#include "ChangeDutyRequest.h"
void ChangeRequest::setSwapDay(int newDay)
{
swapDay = newDay;
}
int ChangeRequest::getSwapDay()
{
return swapDay;
}
void ChangeRequest::setNewDay(int day)
{
newDay = day;
}
int ChangeRequest::getNewDay()
{
return newDay;
}
The code below is for the derived class. SwapDuty
SwapDuty.h
#include <iostream>
#include <string>
#include "ChangeRequest.h"
using namespace std;
class SwapDuty: public ChangeRequest
{
string requester;
public:
void setRequester(string member);
string getRequester();
};
SwapDuty.cpp
#include "SwapDuty.h"
void SwapDuty::setRequester(string member)
{
requester = member;
}
string SwapDuty::getRequester()
{
return requester;
}
when I compile and access the requester attribute using getRequester(). I get the following error.
'class ChangeRequest' has no member named 'getRequester'
This is how I used my code
Can someone please tell me what I am doing wrong? Thanks in advance
SwapDuty newSwapDutyRequest;
for(int i = 0; i < tempList.size(); i++ )
{
if(tempList[i].getPersonToPerform().getName() == loginMember)
{
newSwapDutyRequest.setRequester(loginMember);
newSwapDutyRequest.setSwapDay(swapDay);
newSwapDutyRequest.setNewDutyDay(daySwapWith);
break;
}
}
changeList.push_back(newSwapDutyRequest);
cout << changeList[1].getRequester() << endl;
What is type of changeList?
Although you have created an object of the derived class, I suspect that you are pushing it into the container of the base class. Possibly you are getting few warnings before this error as well, because of pushing derived object into the container of type base.
If you want to make a container of base class and push in the derived class objects you need to work with the pointers to the objects not the objects themselves.
Where is your class ChangeDutyRequest? You don't show it. Maybe you forgot to inherit it from the correct base or invoke it incorrectly?
Show fuller code sample