问两个问题

zengkun100 2006-11-18 10:48:05
问题一:如何阻止一个类被派生?有办法吗?在C#里用关键字sealed可以,C++里怎么搞?

问题二:用模板写个函数min代替MIN宏,要求此函数能够对字符串进行比较
...全文
208 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
westdot 2006-11-18
  • 打赏
  • 举报
回复
nice.
wxspll 2006-11-18
  • 打赏
  • 举报
回复
Bjarne Stroustrup的答案:
Can I stop people deriving from my class?

Yes, but why do you want to? There are two common answers:

for efficiency: to avoid my function calls being virtual
for safety: to ensure that my class is not used as a base class (for example, to be sure that I can copy objects without fear of slizing)
In my experience, the efficiency reason is usually misplaced fear. In C++, virtual function calls are so fast that their real-world use for a class designed with virtual functions do not to produce measurable run-time overheads compared to alternative solutions using ordinary function calls. Note that the virtual function call mechanism is typically used only when calling through a pointer or a reference. When calling a function directly for a named object, the virtual function class overhead is easily optimized away.
If there is a genuine need for "capping" a class hierarchy to avoid virtual function calls, one might ask why those functions are virtual in the first place. I have seen examples where performance-critical functions had been made virtual for no good reason, just because "that the way we usually do it".

The other variant of this problem, how to prevent derivation for logical reasons, has a solution. Unfortunately, that solution is not pretty. It relies on the fact that the most derived class in a hierarchy must construct a virtual base. For example:

class Usable;

class Usable_lock {
friend class Usable;
private:
Usable_lock() {}
Usable_lock(const Usable_lock&) {}
};

class Usable : public virtual Usable_lock {
// ...
public:
Usable();
Usable(char*);
// ...
};

Usable a;

class DD : public Usable { };

DD dd; // error: DD::DD() cannot access
// Usable_lock::Usable_lock(): private member

westdot 2006-11-18
  • 打赏
  • 举报
回复
template<class T>
T min(T arg1, T arg2)
{
return (arg1 < arg2 ? arg1 : arg2);
}

typedef const char* STR;
template<> STR min(STR str1, STR str2)
{
return (strcmp(str1, str2) < 0 ? str1: str2);
}
a_b_c_abc3 2006-11-18
  • 打赏
  • 举报
回复
template <class T>
T& min(T& a,T& b)
{
return a<b?a:b;//对于std::string,这样就行了
}
template <>
char*&min<char*&>(char*& a,char*& b)//对于char*,就这样特化一下
{
return strcmp(a,b)<0?a:b;
}



int main()
{
string str1("1234");
string str2("1256");
cout<<min(str2,str1)<<endl;
cout<<min(str1,str2)<<endl;
char* p1="abcde";
char* p2="abcd";
cout<<min(p1,p2)<<endl;
cout<<min(p2,p1)<<endl;
return 0;
}
westdot 2006-11-18
  • 打赏
  • 举报
回复
阻止一个类被派生?成员全部私有。用友元函数来访问。

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧