C++ member variable pointers
I am sure this is a basic question, but I keep receiving memory access errors when I think I am doing this correctly.
What I want to do:
class A{
string name;
string date;
}
main{
A *a = new A();
a->name= someFunct();
a->date= someFunct();
B b;
}
class B{
A *a;
printf("%s", a->name); //retrieving data set in main
}
I essentially need to assign some overall settings in one class and want to be able to access 开发者_运维百科those settings throughout the application in the most efficient way.
You're passing a std::string to printf, you need to pass a c string.
printf("%s", a->name.c_str())
In addition to Andreas' answer, you are not initialising *a in B. Just because they are named the same does not mean that they are pointing to the same thing. You need to say something like
b.a = new A();
in your main. Otherwise b.a is an empty pointer.
Ie. You need to create an instance of a on your b instance. Alternatively to keep a bit closer to your current code you could do:
int main(char* args[]){
A *a = new A();
a->name= someFunct();
a->date= someFunct();
B b;
B.a = a;
return 0;
}
Maybe this will be useful too:
class A
{
public: //you forgot this
//defaut is private
string name;
string date;
};
int main()
{
A *a = new A();
a->name = someFunct();
a->date = someFunct();
delete a; //maybe you should do it
}
class B
{
A *a;
.....
printf("%s", a->name.c_str());
.....
};
精彩评论