ich ein Problem mit einer Leistung von 2 Klassen haben wie unten:Zeiger auf ein Objekt hat keinen beliebigen Wert (oder nicht bekommen Wert)
foo.h
public:
Foo(){} ;
Foo(string);
Foo(const Foo&);
string getFooName() const;
~Foo();
private:
string foo;
foo.cpp
Foo::Foo(string n):foo(n){
}
Foo::Foo(const Foo &f):foo(f.foo){
}
string Foo::getFooName() const{
return foo;
}
Foo::~Foo(){
}
und Klasse Bar:
bar.h
public:
Bar();
Bar(string, Foo&);
Bar(const Bar&);
Foo& getFoo() const;
~Bar();
private:
string bar;
Foo* foo;
};
Bar.cpp
Bar::Bar(string b, Foo &f):bar(b), foo(new Foo()){
}
Bar::Bar(const Bar &b):bar(b.bar), foo(new Foo(*b.foo)){
}
Foo &Bar::getFoo() const{
return *foo;
}
Bar::~Bar()
{
delete foo;
}
und in Haupt-Funktionen erzeugt, wenn ich diese verwenden cout<<"Test:"<<b->getFoo().getFooName();
wird es mir nur in der Ausgabe nur Test:
statt Test:TestFoo
.
Was ist falsch in meinem Code? (Gcc5.4.0, Cmake 3.5.1) tnx
und main.cpp
Foo* f;
Bar* b;
f=new Foo("TestFoo");
b=new Bar("TestBar",*f);
cout<<"Test:"<<b->getFoo().getFooName(); // this line
Bar :: Bar (String b, Foo & f): bar (b), foo (neu Foo()) {'Ihr Konstruktor' foo' Argument wird ignoriert und eine neue leere 'Foo' Instanz wird immer erzeugt. – Ari0nhh