在C++中通过引用传递对象

use*_*289 0 c++ pass-by-reference

我试图通过const引用将一个对象(类库存)传递给另一个类的函数(称为Algorithms).

//Algorithms.h
#pragma once

class Algorithms
{
public:
    Algorithms(void);
    ~Algorithms(void);
    int Algorithms::doAnalysis(const Stock&);
};
Run Code Online (Sandbox Code Playgroud)

doAnalysis的实现是

#include "StdAfx.h"
#include "Algorithms.h"
#include "Stock.h"
#include <vector>

using namespace std;

Algorithms::Algorithms(void)
{
}

Algorithms::~Algorithms(void)
{
}

int Algorithms::doAnalysis(const Stock &S)
{
    //Do Something
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

类Stock有以下构造函数

public:
    Stock(std::string market, std::string symbol);
    Stock(std::string market, std::string symbol, std::string start_date, std::string  end_date);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Error: declaration is imcompatible with "int Algorithms::doAnalysis(const<error-type> &)" declared at line 8 of  Algorithms.h
Run Code Online (Sandbox Code Playgroud)

我知道没有找到班级股票.我应该如何在Algorithms.h中声明doAnalysis方法以便找到它?股票不是派生类.

谢谢你的帮助.我是C++的新手.

Pie*_*aud 7

您必须添加该类的前向声明Stock:

// Forward declaration
class Stock;

class Algorithms
{
public:
    Algorithms(void);
    ~Algorithms(void);
    int doAnalysis(const Stock&);
  //    ^^ <- Remove the Algorithms::
};
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到为什么在C++中需要前向声明.