程序未调用正确的重载运算符
我有一个类 Directory,它使用类 File 的对象和重载的运算符进行操作,如下所示:
class Directory
{
std::vector<char> name, timeOfCreation;
std::vector<File> arr;
public:
Directory(std::string);
Directory(const Directory&);
~Directory();
Directory operator += (File);
Directory operator += (Directory);
Directory operator -= (File);
Directory operator ~();
File operator [] (int);
operator int();
friend bool operator % (Directory, File);
friend bool operator % (Directory, Directory);
friend Directory operator + (Directory, Directory);
friend Directory operator - (Directory, Directory);
friend long int operator + (Directory);
friend std::ofstream& operator << (std::ofstream&, Directory);
friend void main();
};
时,就会出现问题
void main()
{
//make object of Directory d
std::cout << d;
}
好的,现在当我在主程序中调用运算符 int() 而不是运算符 << 。因此命令
std::cout <
std::cout << (int)d
,它会写出我的目录中的文件数量。
以下是运算符 << 的实现和 int():
Directory::operator int()
{
return (int)arr.size();
}
std::ofstream& operator << (std::ofstream& out, Directory d)
{
// get the max field widths for three fields
int widthLeft = 0, widthMiddle = 0, widthRight = 10;
std::vector<File>::const_iterator i = d.arr.begin();
for(; i < d.arr.end(); ++i)
{
if((int)d.timeOfCreation.size() > widthLeft)
widthLeft = (int)d.timeOfCreation.size();
if((int)d.name.size() > widthMiddle)
widthMiddle = (int)d.name.size();
}
out<<std::setw(widthLeft)<<"Date & Time of creation";
out<<std::setw(widthMiddle)<<"Name";
out<<std::setw(widthRight)<<"Total Size\n";
return out;
}
注意:运算符 <<尚未完成,我只是测试 setw 函数,但它仍然应该写出这一行。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
cout
是一个ostream
,而不是ofstream
。应该可行:
您可能希望传递目录作为参考。
cout
is anostream
, not anofstream
.Should work:
You might want to pass the directory as a reference.
您的重载
<<
应该与基类ostream
一起使用,而不仅仅是ofstream
:std::cout
> 不是ofstream
,因此它与您的重载不匹配。 (通过常量引用而不是值传递复杂对象也是一个好主意)。此外,转换运算符通常不是一个好主意,因为它们可能会引入不需要的隐式转换(就像您在此处发现的那样),而且因为它们可能会使类的用户感到困惑。通过命名函数(
size()
或file_count()
等)查找目录中的文件数量比通过目录本身更有意义神奇地变成那条特定的信息。Your overloaded
<<
should work withostream
, the base class, not justofstream
:std::cout
is not anofstream
, so it will not match your overload. (It's also a good idea to pass complex objects by constant reference rather than value).Also, conversion operators are usually a bad idea, both because they can introduce unwanted implicit conversions like you found here, and because they can confuse the user of the class. It makes more sense to find the number of files in a directory through a named function (
size()
, orfile_count()
, or whatever), than by the directory itself magically changing into that particular piece of information.