[英]Compiling class issue
嘗試編譯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
;' before 'first' testStock.cpp:9: error: 'first' was not declared in this scope testStock.cpp:12: error: expected
;' 在“第二” testStock.cpp:13之前:錯誤:未在此范圍中聲明“第二”
股票.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;
}
我肯定它很明顯,但它只是我的第二類程序。
看來您已省略
#include "stock.h"
從您的testStock.cpp
。
編譯器告訴您“未在此范圍內聲明'Stock'” 。 因此,您應該問自己“在哪里宣布“庫存”? 並且您應該能夠回答: “它在stock.h
聲明” 。
並且“為什么編譯器不知道在stock.h
聲明了'Stock'?” 因為您還沒有包含它。 因此,正如這里已經提到的那樣, #include "stock.h"
是解決方案。
希望您將花費更多的時間閱讀編譯器錯誤/警告,也希望更多的時間嘗試理解它們;)
您只是沒有在主文件中包括"stock.h"
,所以編譯器不知道Stock first
意味着什么。
#include "stock.h"
並且您將能夠創建Stock
對象,因為它對您的TestStock
類是可見的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.