2 gargan Gargan 于 2016.04.10 21:39 提问

从字符串到分数的构造器,在构造器函数的定义处调试时有“写入位置访问冲突”问题

#define _CRT_SECURE_NO_WARNINGS
#include
#include
using namespace std;
class Fraction
{

private:
int num, den;
public:
Fraction(char s[10]);
void set(int n, int d){ num = n; den = d;normalize(); }
int get_x(){ return num; }
int get_y(){ return den; }
private:
void normalize();
int lcd(int a,int b);
};

int main()
{
Fraction p3("12,14");
cout << p3.get_x() << endl;
cout << p3.get_y() << endl;
system("pause");
return 0;
}
Fraction::Fraction(char s[])
{
int n = 0;
int d = 1;
char *p1,*p2;
p1 = strtok(s,"/,");
p2 = strtok(NULL,"/,");
if (p1 != NULL)
{
n = atoi(p1);
}
if (p2 != NULL)
{
d = atoi(p2);
}
set(n, d);
}
void Fraction::normalize()
{
if (num == 0 || den == 0)
{

num = 0;
den = 1;
}
int n = lcd(num,den);
num /= n;
den /= n;
}
int Fraction::lcd(int a,int b)
{
if (b == 0)
{

return a;
}
else return lcd(b,a%b);
}

2个回答

qq423399099
qq423399099   Ds   Rxr 2016.04.10 21:57
已采纳

有两个问题:
1.Fraction p3("12,14");不能这样,因为"12,14"是常量字符串,strtok企图修改常量区就会报异常,要改成栈区或者堆区的字符数组或者字符串
2.p1 = strtok(s,"/,");和p2 = strtok(NULL,"/,");楼主加一个/要干嘛?就算转义也应该是\,而且,是不用转义的
改成p1 = strtok(s,",");p2 = strtok(NULL,",");

 #include <iostream>
using namespace std;
class Fraction
{

private:
    int num, den;
public:
    Fraction(char s[10]);
    void set(int n, int d){ num = n; den = d;normalize(); }
    int get_x(){ return num; }
    int get_y(){ return den; }
private:
    void normalize();
    int lcd(int a,int b);
};
int main()
{
    char str[10] = "12,14";
    Fraction p3(str);
    cout << p3.get_x() << endl;
    cout << p3.get_y() << endl;
    system("pause");
    return 0;
}
Fraction::Fraction(char s[])
{
    int n = 0;
    int d = 1;
    char *p1,*p2;
    p1 = strtok(s,",");
    p2 = strtok(NULL,",");
    if (p1 != NULL)
    {
        n = atoi(p1);
    }
    if (p2 != NULL)
    {
        d = atoi(p2);
    }
    set(n, d);
}
void Fraction::normalize()
{
    if (num == 0 || den == 0)
    {

        num = 0;
        den = 1;
    }
    int n = lcd(num,den);
    num /= n;
    den /= n;
}
int Fraction::lcd(int a,int b)
{
    if (b == 0)
    {

        return a;
    }
    else return lcd(b,a%b);
}
caozhy
caozhy   Ds   Rxr 2016.04.10 21:50

Fraction p3("12,14");
->
char s[100]="12,14";
Fraction p3(s);

Gargan
Gargan 谢谢!
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!