【发布时间】:2011-05-23 09:25:15
【问题描述】:
我有一个:header.cpp、header.hpp 和一个 test_header.cpp。
在 header.hpp 我有:
class MyClass
{
public;
MyClass();
std::string name;
//...code with other variables,methods;
class MySecondClass
{
public:
MySecondClass();
std::string surname;
//..code with other variables,methods
}*MySC;
public:
template<class T>
bool method(T& obj);
{
if (typeid(MyClass)=typeid(obj))
{
MyClass *s= new MyClass();
*s=obj //i want to save everything that i have in obj into s;
//call method "MyMethod" and work with s
}
else if (typeid(MyClass::MySecondClass)=typeid(obj))
{
MyClass::MySecondClass *s1= new MyClass::MySecondClass();
*s1 = obj;
//call "MyMethod" and work with s1;
}
return true;
}
}*mycls;
在 test_header.cpp 我有
{
MyClass *mycls = new MyClass();
MyClass::MySecondClass *mysec_cls= new MyClass::MySecondClass();
if (mycls->method<MyClass>(*mycls)
{//code
}
if (mycls->method<MyClass::MySecondClass>(*mysec_cls)
{//code
}
}
我有一个错误说 mysec_cls 不是 MyClass 类型。正如我意识到的那样,指针指向第一个 if 并且永远不会指向 else。
.h error: no match for operator= in *s1 = obj.
note: candidates are: MyClass& MyClass::operator=(const MyClass&)
如果在 test_header.cpp 我只有一个 if 和 if 在模板中我只有一个来自 test_header 中的 if 的引用,但如果我对 T& obj 有多个引用,我没有这个错误我有错误我已经提到了。
为什么?如何改变这个?我正在使用 g++ 编译。
【问题讨论】:
-
你能修复你的代码 sn-p 上的缩进吗?
-
一个简单的重载将为您节省大量精力的明显案例。无论如何,您的代码难以理解-您需要组合一个更清晰的示例,并且您可能会得到一些答案。 ..
-
从你的问题来看,听起来你已经删除了明显有问题的代码: //using std::type_info& and typeid i get the ype of the obj;在 std::string s 中,我保留了 obj 的名称,然后......
-
这是什么奇怪的语法?
class MyClass {} *mycls;和class MySecondClass {} *MySC;?你希望通过这个实现什么目标? -
@Nim,该语法正在创建类型 (
class MyClass {}) 并创建类型为 pointer-to-newly-created-type 的变量。基本相当于class MyClass {}; class MyClass *mycls;
标签: c++