编译类问题

Compiling class issue

本文关键字:问题 编译      更新时间:2023-10-16

在编译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范围

库存.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

库存.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;
}

我确信这是显而易见的,但这只是我的二等课程。

看起来您忽略了

#include "stock.h"

从您的testStock.cpp

编译器告诉您"‘Stock’未在此范围内声明"。因此,您应该问问自己"‘股票’在哪里申报?",您应该能够回答:"它在stock.h中申报"

"为什么编译器不知道‘Stock’是在stock.h中声明的?" 因为您还没有包括它。所以正如这里已经提到的,#include "stock.h"就是解决方案。

希望你能花更多的时间阅读编译器的错误/警告,也能花更多时间理解它们;)

您只是没有在主文件中包含"stock.h",所以编译器不知道Stock first是什么意思。

#include "stock.h"

并且您将能够创建Stock对象,因为它将对您的TestStock类可见。