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

找错,谢谢

longyou2011 发布于 2011-01-31 16:48, 468 次点击
#include<iostream>
#include<string>
using namespace std ;
class Person
{
public :
    Person ( const Person &p ) ;
    ~Person () ;
    void setAge ( int x ) { age = x ; }
    void print () ;
private :
    char * name ;
    int age ;
} ;

Person :: Person ( const Person &p  )
{
    name = new char [ strlen ( p.name ) + 1 ] ;
    strcpy ( name , p.name ) ;
    age = p.age ;
    cout << " Copy constructor called ! " << endl ;
}
Person :: ~Person ()
{
    cout << " Destructor called ! " << endl ;
    delete name ;
}
void Person :: print () { cout << " name : " << name << " age : "<< age << endl ; }
int main ()
{
    Person p1 ( " 张三 " , 21 ) ;
    Person p2 = p1 ;
    p1.setAge (1) ;
    p2.setAge (2) ;
    p1.print () ;
    p2.print () ;
    return 0 ;
}
错在了哪里
5 回复
#2
zqmillet2011-01-31 20:14
又是lz……

声明里没有相应的两个形参的构造函数
这是完整的代码:
程序代码:

#include<iostream>
#include<string>
using namespace std ;
class Person
{
public :
    Person (const char * n, const int a);  //...............................1
    Person ( const Person &p ) ;
    ~Person () ;
    void setAge ( int x ) { age = x ; }
    void print () ;
private :
    char * name ;
    int age ;
} ;

Person::Person (const char * n, const int a)            //...................2
{
    name = new char [strlen(n) + 1];
    strcpy(name,n);
    age = a;
    return;
}

Person :: Person ( const Person &p  )
{
    name = new char [ strlen ( p.name ) + 1 ] ;
    strcpy ( name , p.name ) ;
    age = p.age ;
    cout << " Copy constructor called ! " << endl ;
}
Person :: ~Person ()
{
    cout << " Destructor called ! " << endl ;
    delete name ;
}
void Person :: print () { cout << " name : " << name << " age : "<< age << endl ; }
int main ()
{
    Person p1 ( " 张三 " , 21 ) ;
    Person p2 = p1 ;
    p1.setAge (1) ;
    p2.setAge (2) ;
    p1.print () ;
    p2.print () ;
    return 0 ;
}


VC提示的很到位啊,怎么会找不到错误呢?
只有本站会员才能查看附件,请 登录
#3
zqmillet2011-01-31 20:16
另:

#include<string>

这句话多余
#4
longyou20112011-01-31 21:45
又是。。。。。谢谢你的多次回答 ,但是用你改正后的代码执行时难道没有出现错误提示框吗? 程序只调用了一次构造函数,但调用了两次析构函数
#5
zqmillet2011-01-31 23:53
以下是引用longyou2011在2011-1-31 21:45:42的发言:

 又是。。。。。谢谢你的多次回答 ,但是用你改正后的代码执行时难道没有出现错误提示框吗? 程序只调用了一次构造函数,但调用了两次析构函数

p1和p2构造了两次啊,那个p1调用的是两个形参的那个构造函数
p2调用的是拷贝构造函数
析构函数也是调用了2次,很正常啊

我用的事故VC6编译的,没有什么问题
截图在2楼
#6
longyou20112011-02-01 09:32
不好意思,我搞错了。厉害厉害
1