为什么这个C++程序运行得这么奇怪,程序在添加空函数时就死了

why this C++ program runs so strange,the program died when added a empty function

本文关键字:程序 函数 添加 运行 C++ 为什么      更新时间:2023-10-16

我的代码如下,path1.updatePathInfo()是一个调用空函数的函数,如果删除它就可以正常工作。我无法理解。

////////////////////////////////////////////////////main.cpp
#include <iostream>
#include<vector>
#include "CPath.h"
using namespace std;
int main()
{
    for(int i = 0;i<10;++i)
    {
        cout<<i;
        CPath path1;
        CPath path2;
        cross(path1,path2);
        path1.updatePathInfo();  //this is an function which call an empty function
                                 //if I delete this it works fine.I could't understand.
        path2.updatePathInfo();
    }
}
//

/

#ifndef CPATH_H_
#define CPATH_H_
#include<iostream>
#include<vector>
#include<fstream>
#include<map>
#include<cmath>
#include<cstdlib>
class CPath
{
public:
    CPath();
    friend void cross(CPath & path1,CPath & path2);
    void updatePathInfo();
    std::vector< int > getPathByCode();
    void createRadomCode();
    std::vector< int > code;
    double pathLineLength;
};
#endif //CPATH_H_
//

.cpp/

#include"CPath.h"
CPath::CPath()
{
    createRadomCode();
}
void cross(CPath & path1,CPath & path2)
{
    int max,min;
    max = rand()%8;
    min = rand()%8;
    if(min > max)
    {
        max ^= min;min ^= max;max ^= min;
    }
    if(0.9*100>rand()%100)
    {
        for(int i = min;i<=max;++i)
        {
            path1.code[i]^=path2.code[i];
            path2.code[i]^=path1.code[i];
            path1.code[i]^=path2.code[i];
        }
    }
}
void CPath::updatePathInfo()
{
    getPathByCode();
}
std::vector< int > CPath::getPathByCode()
{
    //this function has nothing 
}
void CPath::createRadomCode()
{
    for(int i = 0 ; i<8 ; ++i)
    {
        code.push_back(rand()%(i+1));
    }
}
CPath::getPathByCode()

返回值,结果是未定义的行为。 您的编译器不需要告诉您有关此的信息,但是如果您在启用所有警告的情况下进行编译,则几乎肯定会告诉您。

顺便说一句,如果您正确格式化了代码,则此类错误将更容易看到。