为什么出现了这样的错误呢?该怎么解决呢?

代码:
class Calculator {
double operand1, operand2;
char operation;
public:
Calculator(double, double, char
);
double doOperation();
};

#include "Calculator.h"
#include
Calculator::Calculator(double op1, double op2,char* opcode) {
this->operand1 = op1;
this->operand2 = op2;
strcpy_s(operation,10,opcode);
}
double Calculator::doOperation() {
if (strcmp(operation,"div") == 0)
return operand1 / operand2;
else if (strcmp(operation, "plus") == 0)
return operand1 + operand2;
else if (strcmp(operation, "minus") == 0)
return operand1 - operand2;
else if (strcmp(operation, "multi") == 0)
return operand1*operand2;
};
#include
#include "Calculator.h"
#include
using namespace std;
int main(int argc, char *argv[]) {
if (argc != 4) {
cerr << "Please input valid arguments";
return -1;
}
double op1 = atof (argv[2]);
double op2 = atof (argv[3]);
char *opcode = argv[1];
Calculator one(op1, op2, opcode);
double m = one.doOperation();
cout << m<< endl;
return 0;

}



![调试中断的错误](https://img-ask.csdn.net/upload/201705/06/1494043273_141491.png)
![debugger stop](https://img-ask.csdn.net/upload/201705/06/1494043221_345985.png)

首先,代码存在一些错误,修改后的代码如下

Calculator.cpp:

#include "Calculator.h"
#include "stdio.h"
#include "stdlib.h"
#include <cstring>
#include <iostream>
Calculator::Calculator(double op1, double op2, char* opcode) {
    this->operand1 = op1;
    this->operand2 = op2;
    operation = new char[30];
    strcpy_s(operation, 10, opcode);
}
double Calculator::doOperation() {
    if (strcmp(operation, "div") == 0)
        return operand1 / operand2;
    else if (strcmp(operation, "plus") == 0)
        return operand1 + operand2;
    else if (strcmp(operation, "minus") == 0)
        return operand1 - operand2;
    else if (strcmp(operation, "multi") == 0)
        return operand1*operand2;
};

Calculator.h

#pragma once
class Calculator {
    double operand1, operand2;
    char* operation;
public:
    Calculator(double, double, char*);
    double doOperation();
};

主程序:

#include <stdlib.h>  
#include <string.h>  
#include <stdio.h>  
#include <string>  
#include "Calculator.h"
#include <iostream>
using namespace std;

int main(int argc, char *argv[]) 
{
    if (argc != 4) {
        cerr << "Please input valid arguments";
        return -1;
    }
    double op1 = atof(argv[2]);
    double op2 = atof(argv[3]);
    char *opcode = argv[1];
    Calculator one(op1, op2, opcode);
    double m = one.doOperation();
    cout << m << endl;
    return 0;
}

其次,运行此类程序不是简单的按ctrl+F5,而需要接收命令行参数。
方法是先在cmd命令行转到.exe所在目录,然后按照下图中方式加入命令行参数运行。

图片说明

operation 这个参数没有被分配空间啊,strcpy_s(operation,10,opcode);这里不就访问非法内存了吗??