注册 登录
编程论坛 C++教室

求助啊,这段代买在VC++上可以运行,但是DEV c++就不行了

zm你懂 发布于 2012-12-26 22:32, 369 次点击
#include <iostream>
using namespace std;
class sample
{
    char*string;
public:
    sample(){string=new char('\0');}
    sample(const sample &ob);
    ~sample(){if(string) delete string;cout<<"Freeing string\n";}
    void show_string(){cout<<string<<"\n";}
    void set_string(char*s);
    sample operator=(sample &ob);
};
void sample::set_string(char*s)
{
    string=new char[strlen(s)+1];
    if(!string)
    {
        cout<<"Allocation error\n";
        exit(1);
    };
    strcpy(string,s);
}
sample::sample(const sample &ob)
{
    string=new char[strlen(ob.string)+1];
    if(!string)
    {
        cout<<"Allocation error\n";
        exit(1);
    };
    strcpy(string,ob.string);
}
sample sample::operator =(sample &ob)
{
    if(strlen(ob.string)>strlen(string))
    {
        delete string;
        string=new char[strlen(ob.string)+1];
        if(!string)
        {
            cout<<"Allocation error\n";
            exit(1);
        }
    }
    strcpy(string,ob.string);
    return *this;
}
sample input_string()
{
    char instr[80];
    sample str;
    cout<<"Enter a string:";
    cin>>instr;
    str.set_string(instr);
    return str;
}
int main()
{
    sample ob;
    ob=input_string();    //DEV C++中显示这里是错的:no match for 'operator=' in 'ob = input_string()()' ,而VC++中没问题。
    ob.show_string();
    return 0;
}

求大神帮忙改下,能在DEVc++中也运行。
6 回复
#2
rjsp2012-12-27 08:38
错误在于 input_string() 返回了一个临时sample
而 sample sample::operator =(sample &ob) 中要求参数是左值引用

我粗略数了一下,有十数种不同程度的错误,所以没什么好建议你的了
#3
zm你懂2012-12-27 10:03
回复 2楼 rjsp
那为什么VC++上面能够运行呢?
#4
rjsp2012-12-27 10:34
以下是引用zm你懂在2012-12-27 10:03:53的发言:

那为什么VC++上面能够运行呢?

你这个问题就问得哑口无言,我怎么知道为什么有人会说“1+1=3”,难道你一定要我亲口骂一下VC才甘心
#5
liujinyong192012-12-27 11:11
你这个程序错了好多,我随便看了一眼,基本的#include<string>这个没有哇,后面的不说了,你在仔细琢磨琢磨
#6
zm你懂2012-12-27 21:36
回复 5楼 liujinyong19
这个包含在#include<iostream>里了,可以省略啊
#7
zm你懂2012-12-27 21:39
回复 4楼 rjsp
应该有什么原因吧?
我是新手,不懂啦,求大神赐教啊
1