模版例题,运行提示错误:“ error C2679: 二进制“=“.....”。可是重载了"="?

whoyousee 2009-05-02 11:25:05
书上的一个例题,运行没有成功提示:
1>模版stack.cpp
1>g:\vc++9.0\模版stack\模版stack\模版stack.cpp(22) : error C2679: 二进制“=”: 没有找到接受“const MyClass”类型的右操作数的运算符(或没有可接受的转换)
1> g:\vc++9.0\模版stack\模版stack\模版stack.cpp(49): 可能是“MyClass &MyClass::operator =(MyClass &)”


可是有“ MyClass& operator =(MyClass& myc)“这是怎么回事?

#include "stdafx.h"
#include "iostream"
using namespace std;
#include "string.h"
template<class T,int i>class MyStack
{
int CItem;
T StackBuff[i];
public:
MyStack(void):CItem(i)
{}
void push(const T item);
T pop(void);
};

template<class T,int i>void MyStack<T,i>::push(const T item)
{
if(CItem>0)
StackBuff[--CItem]=item;// error C2679: 二进制“=”: 没有找到接受“const MyClass”类型的右操作数的运算符(或没有可接受的转换)
else
throw "stack overflow error";
return;
}

template<class T,int i>T MyStack<T,i>::pop(void)
{
if(CItem<i)
return StackBuff[CItem--];
else
throw "stack underflow error";
}

class MyClass
{
#define MAX_SIZE 10
char text[MAX_SIZE];
public:
MyClass()
{
text[0]='\0';
}
char *get()
{
return text;
}
MyClass& operator =(MyClass& myc)
{
if(&myc==this)
{
return *this;
}
strcpy_s(text,myc.get());
return *this;

}

void set(char *str)
{
if(strlen(str)>=MAX_SIZE)
{
strncpy_s(text,str,MAX_SIZE-1);
str[MAX_SIZE]='\0';
}
else
strcpy_s(text,str);
}
};

typedef MyStack<int,10>Istack;
typedef MyStack<double,10>Fstack;
typedef MyStack<MyClass,20>MYstack;

int _tmain(int argc, _TCHAR* argv[])
{
Istack istack;
Fstack fstack;
MYstack mystack;
int i1,i2;
double f1,f2;
istack.push(1);
istack.push(2);
i1=istack.pop();
i2=istack.pop();
printf("%d,%d",i1,i2);
fstack.push(5.3);
fstack.push(43.3);
f1=fstack.pop();
f2=fstack.pop();
printf("%f,%f",f1,f2);
MyClass str1,str2,str3;
str1.set("abc");
str2.set("aaa");
str3.set("012345678");
printf("%s\n%s\n%s\n",str1.get(),str2.get(),str3.get());
mystack.push(str1);
mystack.push(str2);
mystack.push(str3);
str1=mystack.pop();
str2=mystack.pop();
str3=mystack.pop();
printf("%s\n%s\n%s\n",str1.get(),str2.get(),str3.get());
return 0;
}

...全文
355 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
mengde007 2009-05-02
  • 打赏
  • 举报
回复
0分贴??
whoyousee 2009-05-02
  • 打赏
  • 举报
回复
太爱你了,ok
mengde007 2009-05-02
  • 打赏
  • 举报
回复
参数类型不配的问题;

template<class T,int i>void MyStack<T,i>::push(T item)//注意了;此处你原来是const T item;去掉const
{
if(CItem>0)
StackBuff[--CItem]=item;// 你下面声明的是非const类型的;
else
throw "stack overflow error";
return;
}

MyClass& operator =(MyClass& myc)//你这儿是非const类型的;
{
if(&myc==this)
{
return *this;
}
strcpy_s(text,myc.get());
return *this;

}


64,642

社区成员

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

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