我有一个文件:Base.h
class Base;
class DerivedA : public Base;
class DerivedB : public Base;
/*etc...*/
Run Code Online (Sandbox Code Playgroud)
和另一个文件:BaseFactory.h
#include "Base.h"
class BaseFactory
{
public:
BaseFactory(const string &sClassName){msClassName = sClassName;};
Base * Create()
{
if(msClassName == "DerivedA")
{
return new DerivedA();
}
else if(msClassName == "DerivedB")
{
return new DerivedB();
}
else if(/*etc...*/)
{
/*etc...*/
}
};
private:
string msClassName;
};
/*etc.*/
Run Code Online (Sandbox Code Playgroud)
有没有办法以某种方式将此字符串转换为实际类型(类),以便BaseFactory不必知道所有可能的Derived类,并为每个类都有if()?我可以用这个字符串生成一个类吗?
我认为这可以通过Reflection在C#中完成.C++中有类似的东西吗?
在C++中,我想不出一个我希望从基类继承private/protected的情况:
class Base;
class Derived1 : private Base;
class Derived2 : protected Base;
Run Code Online (Sandbox Code Playgroud)
它真的有用吗?
"虚拟"继承的含义是什么?
我看到以下代码,并且virtual在以下上下文中不理解关键字的含义:
class A {};
class B : public virtual A;
Run Code Online (Sandbox Code Playgroud) 在性能方面,什么会更快?有区别吗?它是平台依赖的吗?
//1. Using vector<string>::iterator:
vector<string> vs = GetVector();
for(vector<string>::iterator it = vs.begin(); it != vs.end(); ++it)
{
*it = "Am I faster?";
}
//2. Using size_t index:
for(size_t i = 0; i < vs.size(); ++i)
{
//One option:
vs.at(i) = "Am I faster?";
//Another option:
vs[i] = "Am I faster?";
}
Run Code Online (Sandbox Code Playgroud) 说我们有:
Class Base
{
virtual void f(){g();};
virtual void g(){//Do some Base related code;}
};
Class Derived : public Base
{
virtual void f(){Base::f();};
virtual void g(){//Do some Derived related code};
};
int main()
{
Base *pBase = new Derived;
pBase->f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
哪个g()会被召唤Base::f()?Base::g()还是Derived::g()?
谢谢...
我可以控制静态对象被破坏的顺序吗?有没有办法强制执行我想要的订单?例如,以某种方式指定我想要最后销毁某个对象,或者至少在另一个静态对象之后销毁?
有什么方法可以通过c#中的SortedDictionary向后(反向)迭代?
或者有没有办法以降序开始定义SortedDictionary?
我可以嵌套try-catch块吗?例如:
void f()
{
try
{
//Some code
try
{
//Some code
}
catch(ExceptionA a)
{
//Some specific exception handling
}
//Some code
}
catch(...)
{
//Some exception handling
}
}//f
Run Code Online (Sandbox Code Playgroud) 我知道我不应该从析构函数中抛出异常.
如果我的析构函数调用一个可以抛出异常的函数,那么如果我在析构函数中捕获它并且不进一步抛出它是否可以?或者它是否会导致中止,我不应该从析构函数中调用这些函数?
请考虑以下情形:
map(T,S*) & GetMap(); //Forward decleration
map(T, S*) T2pS = GetMap();
for(map(T, S*)::iterator it = T2pS.begin(); it != T2pS.end(); ++it)
{
if(it->second != NULL)
{
delete it->second;
it->second = NULL;
}
T2pS.erase(it);
//In VS2005, after the erase, we will crash on the ++it of the for loop.
//In UNIX, Linux, this doesn't crash.
}//for
Run Code Online (Sandbox Code Playgroud)
在我看来,在VS2005中,在"擦除"之后,迭代器将等于end(),因此在尝试增加它时崩溃.在这里呈现的行为中,编译器之间是否存在真正的差异?如果是这样,"擦除"之后的迭代器将在UNIX/Linux中等于什么?
谢谢...
c++ ×9
inheritance ×3
exception ×2
stl ×2
virtual ×2
.net ×1
c# ×1
c++-faq ×1
destruction ×1
destructor ×1
dictionary ×1
factory ×1
iteration ×1
iterator ×1
linux ×1
map ×1
nested ×1
performance ×1
polymorphism ×1
private ×1
protected ×1
reverse ×1
static ×1
throw ×1
try-catch ×1
vector ×1