【发布时间】:2012-09-22 11:53:40
【问题描述】:
主线可以工作吗?也许其他运营商?一些建议? 我认为操作顺序是这里的问题。是否必须使用 b.addA("P"); b.R("P").ref(b.R("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;
}
【问题讨论】:
-
(除其他外)我认为这是错误的:
_as.push_back(A::A(nm));。也许你的意思是_as.push_back(A(nm)); -
@MihaiTodor:我认为这没关系,因为我想存储在我的 A 类型向量中,命名为 _as 我的“子对象”
-
你不能/不应该直接调用类的构造函数,即使 VS2010 似乎允许它。更正后,我仍然在 GCC 中收到一个奇怪的错误,但我不知道为什么。
-
@MihaiTodor:我会打电话给 A(nm);为了创建 A 类型的对象,但它需要 B::A(std::string)
-
所以,是的,原来是it's illegal to have a class method sharing the same name as a class in the same context。你是这个限制的受害者。 GCC 足够聪明,可以禁止你这样做。
标签: c++ class pointers operator-keyword