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

c++ 新手,在vs2015环境下,有的函数用不了,以及安全的函数的用法。

cityrunner 发布于 2016-04-09 16:15, 7162 次点击
程序代码:

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class str
{ private:
    char *p;
public:
    str(char *s)
    {
        p = new char[strlen(s) + 1];
        if (p == NULL)
        {
            cout << "动态内存建立不成功,程序终止" << endl;
            exit(0);
        }
        strcpy(p,s);
        cout << "成功创造了对象" << endl;
        cout << "字符数组的内容是:" << endl;
    }
    ~str()
    {
        if (p)
            delete[]p;
        cout << "撤销对象" << endl;
    }
};
void main()
{
    str m("创建动态内存");
        cout << "main()函数" << endl;


}

将 strcpy(p,s)改为strcpy_s(p,sizeof(p),s)后,表面上是没问题,但是运行起来就出现问题,无法运行。
前辈们求解。
6 回复
#2
alice_usnet2016-04-09 16:30
sizeof(p)你以为是数组的长度?只是指针的长度而已。用strlen
#3
cityrunner2016-04-09 16:51
回复 2楼 alice_usnet
明白了,改过来了。
但是程序编译运行后,我不知道系统是否调用了析构函数~str(),肯定的是~str()中的
cout<<"撤销对象"<<endl; 语句肯定没有执行。请问这个问题该怎么办?
#4
alice_usnet2016-04-09 17:14
回复 3楼 cityrunner
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class str
{ private:
    char *p;
public:
    str(char *s)
    {
        p = new char[strlen(s) + 1];
        if (p == NULL)
        {
            cout << "动态内存建立不成功,程序终止" << endl;
            exit(0);
        }
        strcpy(p,s);
        cout << "成功创造了对象" << endl;
        cout << "字符数组的内容是:" << endl;
    }
    ~str()
    {
        if (p)
            delete[]p;
        cout << "撤销对象" << endl;
    }
};
void test()
{
    str m("创建动态内存");
}
int main()
{
    str m("创建动态内存");
    cout << "main()函数" << endl;
    test();
  return 0;

}
这样就行了
#5
cityrunner2016-04-09 17:58
回复 4楼 alice_usnet
只有本站会员才能查看附件,请 登录

谢谢,程序运行完了之后,就停在这了,怎么才能看到 cout<<"撤销对象"<<endl;  这句语句执行。
#6
alice_usnet2016-04-09 18:01
回复 5楼 cityrunner
只有本站会员才能查看附件,请 登录

我的显示正常
#7
cityrunner2016-04-10 00:52
回复 6楼 alice_usnet
那可能是 编译器不同的缘故吧。
1