编译类问题

时间:2012-02-15 19:41:56

标签: c++ compilation

在尝试编译c ++类程序时继续遇到这些错误。

  

testStock.cpp:在函数'int main()'中:testStock.cpp:8:错误:   'stock'未在此范围内声明testStock.cpp:8:错误:   预期;' before ‘first’ testStock.cpp:9: error: ‘first’ was not declared in this scope testStock.cpp:12: error: expected;'之前   'second'testStock.cpp:13:错误:'second'未在此声明   范围

stock.h

#ifndef STOCK_H
#define STOCK_H
using namespace std;

class Stock
{
 private:
  string symbol;
  string name;
  double previousClosingPrice;
  double currentPrice;
 public:
  Stock(string symbol, string name);
  string getSymbol() const;
  string getName() const;
  double getPreviousClosingPrice() const;
  double getCurrentPrice() const;
  double changePercent();
  void setPreviousClosingPrice(double);
  void setCurrentPrice(double);
};

#endif

stock.cpp

#include <string>
#include "stock.h"

Stock::Stock(string symbol, string name)
{
  this->symbol = symbol;
  this->name = name;
}

string Stock::getSymbol() const
{
  return symbol;
}

string Stock::getName() const
{
  return name;
}

void Stock::setPreviousClosingPrice(double closing)
{
  previousClosingPrice = closing;
}

void Stock::setCurrentPrice(double current)
{
  currentPrice = current;
}

double Stock::getPreviousClosingPrice() const
{
  return previousClosingPrice;
}

double Stock::getCurrentPrice() const
{
  return currentPrice;
}

double Stock::changePercent() 
{
  return ((currentPrice - previousClosingPrice)/previousClosingPrice) * 100;
}

testStock.cpp

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

int main()
{
  Stock first("aapl", "apple");
  cout << "The stock symbol is " << first.getSymbol() << " and the name is " << first.getName() << endl;
  first.setPreviousClosingPrice(130.0);
  first.setCurrentPrice(145.0);
  Stock second("msft", "microsoft");
  second.setPreviousClosingPrice(30.0);
  second.setCurrentPrice(33.0);
  first.changPercent();
  second.changePercent();
  cout << "The change in percent for " << first.getName << " is " << first.changePercent() << endl;
  cout << "The change in percent for " << second.getName << " " << second.getSymbol() << " is " << second.changePercent() << endl;

  return 0;
}

我确定它显而易见,但它只是我的第二课程。

4 个答案:

答案 0 :(得分:3)

看起来你已经省略了

#include "stock.h"

来自testStock.cpp

答案 1 :(得分:2)

编译器告诉你&#34;'Stock'未在此范围内声明&#34; 。所以你应该问问自己 &#34;在哪里&#39;股票&#39;声明?&#34; ,你应该能够回答它: &#34;它在stock.h&#34; < / EM>

&#34;为什么编译器不知道&#39; Stock&#39;在stock.h中声明?&#34; 因为您还没有包含它。正如此处已经提到的那样,#include "stock.h"就是解决方案。

希望您花更多时间阅读编译器错误/警告,并花更多时间来理解它们;)

答案 2 :(得分:1)

您只是不在主文件中包含"stock.h",因此编译器不知道Stock first的含义。

答案 3 :(得分:0)

#include "stock.h"

您将能够创建Stock对象,因为TestStock课程可以看到该对象。