运算符重载时遇到的问题'operator +' is ambiguous

C++语言 码拜 8年前 (2016-04-17) 2048次浏览
#include<iostream>
#include<string>
using namespace std;
class Str
{
    int length;
    char *p;
public:
     Str()
	{
		p=new char[100];
	}
    Str(char *s)
    {
       p=new char [100];
	   strcpy(p,s);
    }
    Str(const Str &obj)
    {
		p=new char [100];
        strcpy(p,obj.getp());
    }
    ~Str()
	{
		delete []p;
	}
    friend Str operator + (const Str &s1,const Str &s2);
    void operator =(const Str &obj);
    char* getp()const
    {
        return p;
    }
    void setp(char *s)
    {
        strcpy(p,s);
    }
    void show()
    {
        length=strlen(p);
        cout<<"length="<<length<<" "<<p<<endl;
    }
};
Str operator+(const Str &s1,const Str &s2)
{
	Str temp;
	strcpy(temp.getp(),s1.getp());
	strcat(temp.getp(),s2.getp());
	return temp;
}
void Str::operator =(const Str &obj)
{
   strcpy(p,obj.getp());
}
int main()
{
    char s1[100],s2[100];
    cin.getline(s1,100);
    cin.getline(s2,100);
    Str A(s1);
    Str B(s2);
    Str C;
	C=A+B;
    C.show();
    return 0;
}

运行时会编译错误,具体错误是error C2593: “operator +” is ambiguous
这问题该怎么样解决

解决方案

20

引用:
Quote: 引用:
Quote: 引用:
Quote: 引用:
Quote: 引用:

运行也是OK的,你用什么编译器测试的?

VC6.0…….

友元函数定义函数放在类内试试

可以了!这是为什么啊?

友元放类里面跟外面运行上有差别吗?

估计是编译器版本的问题,不用纠结这个

20

建议你换一个IDE,VC6太老了,换成VS
地址:http://blog.csdn.net/cometnet/article/details/19551125
假如觉得VS太大就下个轻量级的IDE,例如CODEBLOCKS

20

引用:
Quote: 引用:

运行也是OK的,你用什么编译器测试的?

VC6.0…….

VC6对很多标准的支持都不好


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明运算符重载时遇到的问题'operator +' is ambiguous
喜欢 (0)
[1034331897@qq.com]
分享 (0)