メインのラインは機能しますか? もしかして他のオペレーター?いくつかの提案?ここでは操作の順序が問題だと思います。b.addA("P"); を使用する必要がありますか? bR("P").ref(bR("P")); ?
オブジェクトから他のオブジェクトへの参照を追加し、データベース モデルのようにオブジェクト間の関係を作成したいと考えています。
#include <iostream>
#include <vector>
#include <string>
class A;
class B;
class A{
std::string _name;
std::vector<A*> _refs;
public:
A(std::string="");
A& ref(A&);
std::string name() const;
};
class B{
std::string _name;
std::vector<A> _as;
public:
B(std::string="");
A& addA(std::string);
A& R(std::string);
};
A::A(std::string nm){
_name=nm;
}
A& A::ref(A &a){
for(int i=0; i<_refs.size(); i++)
if(_refs[i]==&a)
return a;
_refs.push_back(&a);
return a;
}
std::string A::name() const{
return _name;
}
B::B(std::string nm){
_name=nm;
}
A& B::addA(std::string nm){
for(int i=0; i<_as.size(); i++)
if(_as[i].name()==nm)
return _as[i];
_as.push_back(A(nm));
return _as[_as.size()-1];
}
A& B::R(std::string nm){
for(int i=0; i<_as.size(); i++)
if(_as[i].name()==nm)
return _as[i];
throw std::string("invaild A");
}
int main(){
B b;
b.addA("P").ref(b.R("P"));
return 0;
}