帮我看看,友元,模板组合使用的问题?(可能还有缺省模板参数问题)
#include <iostream>
using namespace std;
//
class Byte
{
public:
Byte(const unsigned char c):ch_(c) {};
protected:
friend std::ostream& operator<< (std::ostream& out,const Byte& b);
private:
unsigned char ch_;
};
//
std::ostream& operator<< (std::ostream& out,const Byte& b)
{
for (int i = 7; i >= 0; i--)
{
if ( b.ch_ & (1 << i) )
out << '1';
else
out << '0';
}
return out;
}
//
template <typename T>
class MemoryMap
{
public:
MemoryMap(const T& x):data_(x) {};
protected:
friend std::ostream& operator<< (std::ostream& out, MemoryMap<T>& x);
private:
T data_;
};
//
template<typename T>
std::ostream& operator<< (std::ostream& out,MemoryMap<T>& x)
{
MemoryMap<T>* ptr=&x.data_;
size_t length=sizeof(x.data_);
Byte* p=reinterpret_cast<Byte*>(ptr);
for (size_t i=0;i<length;i++)
{
out<<*p++<<' ';
if (i>4 && i%4=0 ) out<<'\n';
}
return out;
}
//
int main()
{std::string s="\00a";
cout << s<< endl;
MemoryMap<std::string> mm(s);
cout<< mm<<endl;
return 0;
}
using namespace std;
//
class Byte
{
public:
Byte(const unsigned char c):ch_(c) {};
protected:
friend std::ostream& operator<< (std::ostream& out,const Byte& b);
private:
unsigned char ch_;
};
//
std::ostream& operator<< (std::ostream& out,const Byte& b)
{
for (int i = 7; i >= 0; i--)
{
if ( b.ch_ & (1 << i) )
out << '1';
else
out << '0';
}
return out;
}
//
template <typename T>
class MemoryMap
{
public:
MemoryMap(const T& x):data_(x) {};
protected:
friend std::ostream& operator<< (std::ostream& out, MemoryMap<T>& x);
private:
T data_;
};
//
template<typename T>
std::ostream& operator<< (std::ostream& out,MemoryMap<T>& x)
{
MemoryMap<T>* ptr=&x.data_;
size_t length=sizeof(x.data_);
Byte* p=reinterpret_cast<Byte*>(ptr);
for (size_t i=0;i<length;i++)
{
out<<*p++<<' ';
if (i>4 && i%4=0 ) out<<'\n';
}
return out;
}
//
int main()
{std::string s="\00a";
cout << s<< endl;
MemoryMap<std::string> mm(s);
cout<< mm<<endl;
return 0;
}
...全文
相关推荐
友元.docx
在实际编程过程中,应该尽量避免过度使用友元,特别是在面向对象的设计中,应优先考虑使用继承和组合等更优雅的方式来解决问题。
C++模拟试卷_2021_答案1
关于函数的所有缺省参数的叙述正确的是B. 只能出现在参数表的最右边。在 C++ 中,缺省参数只能出现在参数表的最右边,以免引起歧义。5.
c++面试题整理+答案.docx
解释:友元的作用是加强类的封装性,使得类更加安全。9. 在 C++中,关于下列设置缺省参数值的描述中,( )是正确的。答案:B、在指定了缺省值的参数右边,不能出现没有指定缺省值的参数。
面向对象程序设计实验指导书版.doc
本指导书覆盖了四个关键的实验,分别涵盖了C++语言的面向对象特性,包括类与对象、继承与组合、多态性、友元、虚函数以及模板的使用。
C++继承与组合详解[源码]
然而,多继承可能导致所谓的菱形继承问题,即当两个基类又共同继承自一个更高级的类时,派生类可能会有多份基类成员的副本。为解决这一问题,C++提供了虚继承的概念。


